原生AJAX
- 创建对象
const xhr = new XMLHttpRequest();
- 初始化
xhr.open();
- 发送
xhr.send();
- 事件绑定
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status >= 200 && xhr.status <300){
result.innerHTML = xhr.response
}
}
}
const btn = document.getElementsByTagName('button')[0];//绑定事件btn.onclick = function(){//1.创建对象const xhr = new XMLHttpRequest();//2.初始化 设置请求方法和urlxhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200');//3.发送xhr.send();//4.事件绑定 处理服务端返回的结果//readystate 是xhr对象中的属性,表示状态 0 1 2 3 4/*0 未初始化1 open方法已经调用完毕2 send方法已经调用完毕3 终端返回了部分接口4 终端返回了所有接口*/xhr.onreadystatechange = function(){//判断(服务端返回了所有的结果)if(xhr.readyState === 4){//判断响应状态码//2xx 成功if(xhr.status >= 200 && xhr.status < 300){//处理结果 行 头 空行 体// 响应// console.log(xhr.status)// console.log(xhr.statusText)//状态字符串// console.log(xhr.getAllResponseHeaders());//所有响应头// console.log(xhr.response);//响应体//设置result的文本result.innerHTML = xhr.response;}else{}}}}
取消请求 abort()
<button>点击发送</button><button>点击取消</button><script>const btns = document.querySelectorAll('button');let x = null;btns[0].onclick = function(){x = new XMLHttpRequest;x.open('GET','http://127.0.0.1:8000/delay');x.send();}//abortbtns[1].onclick = function(){x.abort();}</script>
JQuery发送AJAX请求
$.ajax({//urlurl:'http://127.0.0.1:8000/jquery-server',//参数data:{a:100,b:200},//请求类型type:'GET',//响应体结果设置dataType:'json',//成功的回调success:function(data){console.log(data);},//超时事件timeout:2000,//失败的回调error:function(){console.log('出错啦');},//头信息headers:{c:300,d:400,}})
//jQuery服务app.all('/jquery-server',(request,response)=>{//设置响应头 设置允许跨域response.setHeader('Access-Control-Allow-Origin','*');response.setHeader('Access-Control-Allow-Headers','*');// response.send('Hello jQuery AJAX')const data = {name:'尚硅谷'};response.send(JSON.stringify(data));});
Axios发送AJAX请求
const btns = document.querySelectorAll('button');//配置baseURLaxios.defaults.baseURL = 'http://127.0.0.1:8000';btns[0].onclick = function(){//GET 请求axios.get('/axios-server',{//url参数params:{id:100,vip:7},//请求头信息headers:{name:'atguigu',age:20}}).then(value => {console.log(value);});}btns[1].onclick = function(){axios.post('/axios-server',{username:'admin',password:'admin'},{//urlparams:{id:200,vip:9},//请求头参数headers:{height:108,weight:180,}})}btns[2].onclick = function(){axios({//urlurl:'/axios-server',//url参数params:{vip:10,level:30},//头信息headers:{a:100,b:200},//请求体参数data:{username:'admin',password:'admin'}}).then(response=>{console.log(response);//响应状态码console.log(response.status);//响应状态字符串console.log(response.statusText);//响应头信息console.log(response.headers);//响应体console.log(response.data);})}
//axios服务app.all('/axios-server',(request,response)=>{//设置响应头 设置允许跨域response.setHeader('Access-Control-Allow-Origin','*');response.setHeader('Access-Control-Allow-Headers','*');// response.send('Hello jQuery AJAX')const data = {name:'尚硅谷'};response.send(JSON.stringify(data));});
fetch函数发送AJAX请求
const btn = document.querySelector('button');btn.onclick = function(){fetch('http://127.0.0.1:8000/fetch-server',{//请求方法method:'POST',//请求头headers:{name:'atguigu'},//请求体body:'username=admin&password=admin'}).then(response=>{return response.json();}).then(response=>{console.log(response);})}
//fetch服务app.all('/fetch-server',(request,response)=>{//设置响应头 设置允许跨域response.setHeader('Access-Control-Allow-Origin','*');response.setHeader('Access-Control-Allow-Headers','*');// response.send('Hello jQuery AJAX')const data = {name:'尚硅谷'};response.send(JSON.stringify(data));});
跨域
同源策略
协议(eg.http)、域名(eg:a.com)、端口号(eg.8000) 完全相同。
违背同源策略就是跨域。
解决跨域
JSONP(只支持get请求)
在网页有一些标签天生具有跨域能力,如img,link,iframe,script.
JSONP就是利用script标签的跨域能力来发送请求的。
CORS 跨域资源共享
配置代理(proxy)
代理,也称正向代理,是指一个位于客户端和目标服务器(target server)之间的服务器,为了从目标服务器取得内容,客户端向代理发送一个请求并指定目标(目标服务器),然后代理向目标服务器转交请求并将获得的内容返回给客户端。
