js实现ajax的原理:通过XMLHttpRequest对象向服务器发送异步请求,从服务器获得数据,然后使用js操作DOM更新数据。该对象是ajax的核心机制,他是在IE5中首先引入的,是一种支持异步请求的技术。通过ajax可以及时的向服务器提出请求和处理响应,而不阻塞用户,达到无刷新更新部分页面的效果。
XMLHttpRequest这个对象的属性有 onreadystatechange 每次状态改变所触发事件的事件处理程序;
responseText 从服务器进程返回数据的字符串形式;
responseXML 从服务器进程返回的DOM兼容的文档数据对象;
status 从服务器返回的数字代码,常见的200(客户端请求成功,已就绪)和404(请求资源不存在)
statusText 伴随状态码的字符串信息 (eg:200 OK)
readyState 对象状态值 0(未初始化状态)对象已建立或已被abort()方法重置,尚未调用open方法。
1(初始化状态)open()方法已经调用,但是send()方法为调用。请求还没有被发送。
2(发送数据)send()方法法以调用,HTTP请求已发送到Web服务器。未接收到响应。
3(数据传送中)所有响应头部都已经接收到。响应体开始接受但未完成。
4(完成加载)HTTP响应已经完全接收。
代码实现
var _url=www.***.com;//请求地址
function ajax(conf) { //ajax封装,url参数必填,var url=conf.url.indexOf('http://')>=0 || conf.url.indexOf('https://')>=0?conf.url:(_url+conf.url);
var data=conf.data;
var send_data=[];//封装后的数据
var async=conf.async!=undefined ? conf.async : true;// ture为异步请求
var type=conf.type || 'get';
var dataType=conf.dataType || 'json';
var contenType = conf.contenType || 'application/x-www-form-urlencoded';
var beforeSend=conf.beforeSend;//post请求头部
var success=conf.success;
var error=conf.error;
if(data==null){
send_data="";
}else if( typeof data=="object"){//如果data是对象,转换为字符串
for (var k in data){
//send_data.push(k + '=' + data[k]);
send_data.push(encodeURIComponent(k) + '=' + encodeURIComponent(data[k]));
}
send_data=send_data.join('&');
}
var xhr=""; // 创建ajax引擎对象
try {
xhr=new ActiveXObject("microsoft.xmlhttp"); //IE内核系列浏览器
}catch(e1){
try {
xhr=new XMLHttpRequest(); //非IE内核浏览器
}catch(e2){
if(error!=null){error("您的浏览器不支持ajax!请更换!");}
}
}
if(type=="get"){
xhr.open(type,url+'?'+send_data,async);
xhr.send(null);
}else{//post,put,delete等请求
xhr.open(type,url,async);
xhr.setRequestHeader("content-type",contenType);
if(beforeSend!=null && beforeSend!=undefined){
beforeSend(xhr);
}
xhr.send(send_data);
}
xhr.onreadystatechange=function() {
if(xhr.readyState==4){
if(xhr.status>=200 && xhr.status<300){
if(dataType=="text" && success!=null){
success(xhr.responseText);
};
if(dataType=="xml" && success!=null){
success(xhr.responseXML);
};
if(dataType=="json" && success!=null){
success(eval("(" + xhr.responseText + ")")); //将json字符串转换为js对象
};
}else{
if(error!=null){error("通讯失败!请联系网站管理员,错误代码:"+xhr.status);}
}
}
};
},
使用方法
ajax({
url:'',//地址
type:'post',//方式
data:{},//数据
success:function(r){
},error:function(r){
}
});