Ajax笔记
特点
1、优点
-
可以无需刷新界面而与服务器进行通信
-
允许根据你用户事件来更新部分页面内容
2、缺点
-
没有浏览历史,不能回退
-
存在跨域问题(同源)
-
SEO不友好
ajax的使用
一、基本使用
// 引入express const express = require('express'); // 创建应用对象 const app = express(); // 创建路由规则 // request 是对请求报文的封装 // response 是对响应报文的封装 app.get('/',(request,response)=>{ // 设置响应 response.send("hello express"); }); // 4、监听端口启动服务 app.listen(8000,()=>{ console.log("服务已经启动,8000端口监视中····"); });
二、Ajax发送GET请求
1、service.js
// 引入express const express = require('express'); // 创建应用对象 const app = express(); // 创建路由规则 // request 是对请求报文的封装 // response 是对响应报文的封装 app.get('/service',(request,response)=>{ // 设置响应头 设置允许跨越 response.setHeader('access-Control-Allow-Origin','*') // 设置响应体 response.send('hello ajax') }); // 4、监听端口启动服务 app.listen(8000,()=>{ console.log("服务已经启动,8000端口监视中····"); });
2、1-GET.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Ajax GET 请求</title> <style> #result{ width: 200px; height: 100px; border: solid 1px #990; } </style> </head> <body> <button>点击发送请求</button> <div id="result"></div> <script> // 获取button元素 const btn = document.getElementsByTagName('button')[0]; const result = document.getElementById('result'); // 绑定事件 btn.onclick = function(){ // 1、创建对象 const xhr = new XMLHttpRequest(); // 初始化 设置请求方法和 url xhr.open('GET','http://127.0.0.1:8000/service'); // 3、发送 xhr.send(); // 事件绑定 处理服务端返回的结果 // on when当...什么时候 // readystate 是xhr对象中的属性,表示状态 0 1 2 3 4 // change 改变的时候出发 xhr.onreadystatechange = function(){ // 判断(服务器返回了所有结果) if (xhr.readyState === 4) { // 判断状态码 200 404 403 401 500 if (xhr.status >=200 && xhr.status <=300) { // 处理结果 行 头 空行 体 // 1、响应行 // console.log(xhr.status);//状态码 // console.log(xhr.statusText);//状态字符串 // console.log(xhr.getAllResponseHeaders());//所有响应头 // console.log(xhr.response);//响应体 // 设置网页文本框的内容 result.innerHTML = xhr.response; } else { } } } } </script> </body> </html>
3、在Ajax请求中设置url的参数
xhr.open('GET','http://127.0.0.1:8000/service?a=100&b=200&c=300');
三、Ajax发送POST请求
service.js
// 引入express const express = require('express'); // 创建应用对象 const app = express(); // 创建路由规则 // request 是对请求报文的封装 // response 是对响应报文的封装 app.get('/service',(request,response)=>{ // 设置响应头 设置允许跨越 response.setHeader('access-Control-Allow-Origin','*'); // 设置响应体 response.send('hello ajax'); }); // 4、监听端口启动服务 app.listen(8000,()=>{ console.log("服务已经启动,8000端口监视中····"); });
2、2-POST.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Ajax POST 请求</title> </head> <style> #result{ width: 200px; height: 100px; border: 1px solid #090; } </style> <body> <div id="result"></div> <script> //获取元素对象 const result = document.getElementById('result'); // 绑定事件 result.addEventListener('mouseover',function(){ // 创建对象 const xhr = new XMLHttpRequest(); // 初始化 设置类型与url xhr.open('POST','http://127.0.0.1:8000/service'); // 发送 xhr.send(); // 绑定事件 xhr.onreadystatechange = function(){ // 判断 if (xhr.readyState === 4) { if(xhr.status>=200 && xhr.status <300){ // 处理服务端返回的结果 result.innerHTML = xhr.response; } } } }); </script> </body> </html>
3、在Ajax中POST请求中设置url的参数(请求体)
xhr.send('a=100& b=200& c=300');
4、Ajax设置请求头
-
预定义
xhr.open('POST','http://127.0.0.1:8000/service') // 设置请求头 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
-
非预定义
xhr.setRequestHeader('name','itxiaoli');
service.js
//可以接受任何类型的请求 app.all('/service',(request,response)=>{ // 设置响应头 设置允许跨越 response.setHeader('access-Control-Allow-Origin','*') //响应头 response.setHeader('access-Control-Allow-Headers','*') // 设置响应体 response.send('hello ajax POST') });
四、Ajax服务端响应JSON数据
service.js
app.all('/json-service',(request,response)=>{ // 设置响应头 设置允许跨越 response.setHeader('access-Control-Allow-Origin','*'); // 设置响应体 response.send('hello ajax JSON'); });
3-JSON.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>JSON数据</title> </head> <style> #result{ width: 200px; height: 100px; border: 1px solid #090; } </style> <body> <div id="result"></div> <script> // 获取数据元素 const result = document.getElementById('result'); // 绑定事件 window.onkeydown = function() { // 发送请求 const xhr = new XMLHttpRequest(); // 初始化 xhr.open('GET','http://127.0.0.1:8000/json-service'); // 发送 xhr.send(); // 事件绑定 xhr.onreadystatechange = function() { if(xhr.readyState === 4){ if(xhr.status >=200 && xhr.status<300){ result.innerHTML = xhr.response; } } } } </script> </body> </html>
五、响应一个数据
//相应一个数据 const data = { name : 'itxiaoli' };
1、对对象进行字符串转换
// 对对象进行字符串转换 let str = JSON.stringify(data); // 设置响应体 response.send(data);
2、手动对数据进行转换
let data = JSON.parse(xhr.response); console.log(data); result.innerHTML = data.name;
3、自动转换
// 设置响应体数据的类型 xhr.responseType = 'json';
五、Ajax的IE缓存的处理
xhr.open('GET','http://127.0.0.1:8000/json-service?t='+Data().now());
六、请求超时与网络异常
//超时2S设置(取消) xhr.timeout = 2000; //超时回调 xhr.ontimeout = function(){ alter("连接超时,请稍后重试!") } //网络异常回调 xhr.onerror = function(){ alter("你的网络似乎出现了问题,请检查你的网络!"); }
七、Ajax取消请求
xhr.abort();
八、重复请求问题
//标识变量 let isSanding = false; //判断是否正在发送Ajax请求 btns[0].onclick = function(){ //判断标识变量 if(isSanding){ xhr.abort(); //如果正在发送,则取消Ajax请求 } const xhr = new XMLHttpRequest(); isSending = ture; xhr.open('GET','http://127.0.0.1.8000/service'); xhr.send(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ //修改标识符变量 isSending = false; } } }
九、jQuery通用发送Ajax请求
$.ajax({ //url url:''http:127.0.0.1:8000/service', //参数 data:{a:100,b:200}, //请求类型 type:'GET', //响应体结果 dataType : 'json', //成功的回调 success: function(){ console.log(data), } //超时时间 timeout: 2000, //失败的回调 error:function(){ console.log('出错了!!!'); }, //头信息 headers:{ c:300, d:400 } });
十、AXIOS发送Ajax请求
//配置 baseURL axios.defaults.baseURL = 'http://127.0.0.1:8000'; btn[0].onclick = function(){ //GET请求 axios.get('/axios-service', { //url参数 params:{ id:100, vip:1 }, //头信息 headers:{ name:'itxiaoli', age:20 }, //请求体参数 data:{ username:'root', passworld:'root' } }).then(response=>{ console.log(response); //响应状态码 console.log(response.status); //响应状态字符串 console.log(response.statusText); //响应头信息 console.log(response.headers); //响应体 console.log(response.data); }) }
十一、fetch函数发送Ajax请求
btn.onclick = function(){ fetch('http://127.0.0.1:8000',{ //请求方法 method:'POST', //请求头 headers:{ name:'itxiaoli' }, //请求体 body:'username = admin&password=root' }
十二、跨域
1、JSONP(非官方,只能发送get请求)
-
原生JSONP跨域的实现
//声明handle函数 function handle(data){ input.style.border = "solid 1px #f00"; //修改p标签的提示文本 p.innerHTML = data.msg; } //绑定事件(失去焦点时) input.onblur = function(){ //获取用户输入的值 let username = this.value; //向服务器端发送请求,检测用户是否存在 //1、创建script标签 const script = document.creatElement('script'); //2、设置标签的src属性 script.src = 'http://127.0.0.1:8000/check-username'; }
//检测用户是否存在 app.all('check-username',(requst,reponse))=>{ const data = { exist:1, mag = '用户名已存在' }; //将数据转化为字符串 let str = JSON.stringify(data); //返回结果 response.end('handle(${str})'); }
-
jQuery发送JSONP
$('button').eq(0).click(function(){ //callback参数必须写 $.getJSON('http://127.0.0.1:8000/jquery-jsonp-service?callback=?)',function(data){ $('#result').html(' 姓名:$(data.name)<br>, 校区:$(data.city) ') }); })
app.all('jquery-jsonp-service',(requst,reponse))=>{ const data = { name:'itxiaoli', city:['哈尔滨','通辽'] }; //将数据转化为字符串 let str = JSON.stringify(data); //接收callback参数 let cb = request.query.callback; //返回结果 response.end('${cb}(${str})'); }
2、CORS(官方)
// 设置响应头 设置允许跨越 response.setHeader('access-Control-Allow-Origin','*'); response.setHeader('access-Control-Allow-Headers','*'); response.setHeader('access-Control-Allow-Method','*');