原生与jQuery封装的ajax请求数据及状态码
原生Ajax 请求数据
btn.addEventListener('click',function(){
if(window.XMLHttpRequest){
var xhr = new window.XMLHttpRequest();
}else{
//兼容IE浏览器
var xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
//请求方式get/post
//请求URL
//ture 异步请求;false 同步请求
xhr.open('get','/ajax/getdata',true);
//给xhr 绑定事件监听状态的改变(状态码见下)
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log(xhr.responseText);
}
}
//发送请求数据 //get方法send参数为空或null
xhr.send();
});
jQuery 实现的Ajax 封装
//jQuery $('.btn').on('click',function(){ $.ajax({ url:'/ajax/getdata', type:'get', dataType:'json', //成功执行函数 success:function(response,status){ console.log(responseText); } }); });
xhr.readystate 状态码
0:unsend //当前请求还未发送
1:opened //URL地址已经打开
2:headers_received //响应头信息已经接收
3:loading // 主要的返回数据正在服务器进行准备处理
4:done //响应主体的内容已经成功返回客户端
xhr.status 服务器状态码
200及以2开头的:成功(响应的主体已经成功返回客户端)
301:永久重定向/转移
302:临时重定向/转移
304:本次获取的内容是读取的缓存
400:客户端->服务器的参数错误
401:无权限访问
404:访问地址不存在
500:未知的服务器错误
501:服务器超负荷
//数据不全仅供参考----------
码农随笔防失忆,只为记录风雨路上的脚丫印印~

浙公网安备 33010602011771号