Ajax
解决跨域
1.设置跨域属性的响应头
- response.setHeader(‘Access-Controll-Allow-Origin’.’*’);
2.jsonp(利用一些h5标签可以跨域的特性发送请求)
发送异步请求
Get请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const xhr = new XMLHttpRequest(); xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=100');
xhr.responseType = 'json';
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if(xhr.status >= 200 && xhr.status < 300){ console.log(xhr.response); } }
}
|
Post请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const xhr = new XMLHttpRequest(); xhr.open('POST','http://127.0.0.1:8000/server');
xhr.responseType = 'json';
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send('a=100&b=100'); xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if(xhr.status >= 200 && xhr.status < 300){ console.log(xhr.response); } }
}
|
请求处理
请求超时
1 2 3 4 5 6 7 8 9 10
| xhr.timeout = 2000;
xhr.ontimeout = function(){ alert("请稍后重试!"); }
xhr.onerror = function(){ alert("你的网络似乎出了问题!"); }
|
取消请求
解决请求重复发送
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| let isSending = false; btn[0].onclick = function(){ if(isSending) x.abort(); const xhr = new XMLHttpRequest(); isSending = true; xhr.open('GET','http://127.0.0.1:8000/server'); xhr.send(); xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ isSending = false; } } }
|
jQuery发送异步请求
1 2
| $.get('http://127.0.0.0:8080/server',{a:100,b:200},function(data){console.log(data);},'json'); $.post('http://127.0.0.0:8080/server',{a:100,b:200},function(data){console.log(data);},'json');
|
通用方式
1 2 3 4 5 6 7 8 9 10 11 12 13
| $.ajax({ url:'http://127.0.0.0:8080/server', data:{a:100,b:200}, type:'GET', dataType:'json', success:function(data){ console.log(data); }, timeout:2000, error:function(){ alert("请稍后重试!"); } })
|