赞
踩
ie浏览器会对ajax请求结果做缓存,下一次发送请求的时候走的是本地的缓存不是最新数据,这样对于时效性强的ajax请求不能正确显示。
在请求路径中加上时间:
xhr.open('GET','http://127.0.0.1:8000/ie?t='+Date.now());
完整代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>IE缓存问题</title> <style> #result{ width:200px; height: 100px; border: solid 1px #258; } </style> </head> <body> <button>点击发送请求</button> <div id="result"></div> <script> const btn=document.getElementsByTagName('button')[0]; const result=document.querySelector('#result'); btn.addEventListener('click',function(){ const xhr=new XMLHttpRequest() xhr.open('GET','http://127.0.0.1:8000/ie?t='+Date.now()); xhr.send(); xhr.onreadystatechange=function(){ if(xhr.readyState===4){ if(xhr.status>=200 && xhr.status<300){ result.innerHTML=xhr.response; } } } }) </script> </body> </html>
请求超时与网络异常:
//超时设置2s
xhr.timeout=2000;
//超时回调
xhr.ontimeout=function(){
alert("网络异常,请稍后重试!")
}
//网络异常
xhr.onerror=function(){
alert("你的网络似乎出了一些问题")
}
app.get('/delay',(req,res)=>{
//设置响应头 设置允许跨域
res.setHeader('Access-Control-Allow-Origin','*');
setTimeout(()=>{
//设置响应体
res.send('延时响应')
},3000)
//设置响应体
// res.send('hhello ie');
})
全部代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>请求超时与网络异常</title> <style> #result{ width: 200px; height: 100px; border: solid 1px #90b; } </style> </head> <body> <button>点击发送请求</button> <div id="result"></div> <script> const btn=document.getElementsByTagName('button')[0]; const result=document.querySelector('#result'); btn.addEventListener('click',function(){ const xhr=new XMLHttpRequest() //超时设置2s xhr.timeout=2000; //超时回调 xhr.ontimeout=function(){ alert("网络异常,请稍后重试!") } //网络异常 xhr.onerror=function(){ alert("你的网络似乎出了一些问题") } xhr.open('GET','http://127.0.0.1:8000/delay'); xhr.send(); xhr.onreadystatechange=function(){ if(xhr.readyState===4){ if(xhr.status>=200 && xhr.status<300){ result.innerHTML=xhr.response; } } } }) </script> </body> </html>
取消请求,发送请求后点取消:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>取消请求</title> </head> <body> <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(); } //abort btns[1].onclick=function(){ x.abort(); } </script> </body> </html>
重复发送请求时,先判断前面有没有一样的请求,有的话就先取消前面的请求再发送新的请求,防止服务器短时间接收大量的请求,压力过大。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>重复请求问题</title> </head> <body> <button>点击发送</button> <!-- <button>点击取消</button> --> <script> //获取元素对象 const btns=document.querySelectorAll('button') let x=null; //标识变量 let isSending=false;//是否发送AJAX请求 btns[0].onclick=function(){ //判断标识变量 if(isSending) x.abort();//如果正在发送,则取消该请求,创建一个新的请求 x=new XMLHttpRequest() //修改标识变量的值 isSending=true; x.open('GET','http://127.0.0.1:8000/delay'); x.send(); x.onreadystatechange=function(){ if(x.readyState===4){ //修改表示变量 isSending=false; } } } //abort btns[1].onclick=function(){ x.abort(); } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery 发送 AJAX 请求</title> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script> </head> <body> <div class="container"> <h2 class="page-header">jQuery发送AJAX请求</h2> <button class="btn btn-primary">GET</button> <button class="btn btn-danger">POST</button> <button class="btn btn-info">通用型方法ajax</button> </div> <script> $('button').eq(0).click(function(){ $.get('http://127.0.0.1:8000/jquery-server',{a:100,b:200},function(data){ console.log(data); },'json') }) $('button').eq(1).click(function(){ $.post('http://127.0.0.1:8000/jquery-server',{a:100,b:200},function(data){ console.log(data); }) }) </script> </body> </html>
使用了bootstrap模板,引入jquery,发送get和post请求,get请求数据会显示在url上,post不会。可以规定接收响应数据类型:
$.get('http://127.0.0.1:8000/jquery-server',{a:100,b:200},function(data){
console.log(data);
},'json')
规定接收json对象的话:
//jquery服务
app.all('/jquery-server',(req,res)=>{
//设置响应头 设置允许跨域
res.setHeader('Access-Control-Allow-Origin','*');
const data={name:'hoshi'}
//设置响应体
res.send(JSON.stringify(data));
})
接受的到响应数据就是对象格式,如果不设置就会是字符串:
$('button').eq(1).click(function(){
$.post('http://127.0.0.1:8000/jquery-server',{a:100,b:200},function(data){
console.log(data);
})
})
ajax:
$('button').eq(2).click(function(){ $.ajax({ //url url:'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',(req,res)=>{
//设置响应头 设置允许跨域
res.setHeader('Access-Control-Allow-Origin','*');
//响应头
res.setHeader('Access-Control-Allow-Headers','*');
const data={name:'hoshi'}
//设置响应体
setTimeout(()=>{
res.send(JSON.stringify(data));
},1000)
})
axios-ajax:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>axios 发送 ajax请求</title> <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/1.7.2/axios.js"></script> </head> <body> <button>GET</button> <button>POST</button> <button>AJAX</button> <script> const btns=document.querySelectorAll('button'); //配置baseURL axios.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:'hoshi', age:20 } }).then(value=>{ console.log(value); }) } btns[1].onclick=function(){ axios.post('/axios-server',{ username:'admin', password:'admin' },{ //url参数 params:{ id:100, vip:7 }, //请求头信息 headers:{ height:180, weight:180 } }); } </script> </body> </html>
server.js
//axios服务
app.all('/axios-server',(req,res)=>{
//设置响应头 设置允许跨域
res.setHeader('Access-Control-Allow-Origin','*');
//响应头
res.setHeader('Access-Control-Allow-Headers','*');
const data={name:'hoshi'}
res.send(JSON.stringify(data))
//设置响应体
// setTimeout(()=>{
// res.send(JSON.stringify(data));
// },1000)
})
fetch发送ajax请求:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>fetch发送ajax请求</title> </head> <body> <button>AJAX请求</button> <script> const btn=document.querySelector('button') btn.onclick=function(){ fetch('http://127.0.0.1:8000/fetch-server?vip=10',{ //请求方法 method:'POST', //请求头 headers:{ name:'hoshi' }, //请求体 body:'username=admin&password=admin' }).then(response=>{ // return response.text(); return response.json(); }).then(response=>{ console.log(response); }) } </script> </body> </html>
//fetch服务
app.all('/fetch-server',(req,res)=>{
//设置响应头 设置允许跨域
res.setHeader('Access-Control-Allow-Origin','*');
//响应头
res.setHeader('Access-Control-Allow-Headers','*');
const data={name:'hoshi'}
res.send(JSON.stringify(data))
})
要打印响应体,需要先调用响应体的text()方法或json()方法,根据返回的是字符串还是json对象决定。
fetch('http://127.0.0.1:8000/fetch-server?vip=10',{
//请求方法
method:'POST',
//请求头
headers:{
name:'hoshi'
},
//请求体
body:'username=admin&password=admin'
}).then(response=>{
// return response.text();
return response.json();
}).then(response=>{
console.log(response);
})
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。