- 以下是ajax的封装函数(js文件),可以直接调用到HTML页面;
[html]
function ajax(obj){ <!--创建XMLHttpRequest对象(即ajax对象)--> if(window.XMLHttpRequest){ var xhr = new XMLHttpRequest; <!--兼容IE5、IE6之外的浏览器--> }else{ var xhr = new ActiveXObject('Microsoft.XMLHTTP'); <!--兼容IE5、IE6浏览器--> } if(obj.type == 'get' || obj.type == 'GET'){ <!--连接服务器--> xhr.open(obj.type,obj.url + '?' +obj.data+'&_='+new Date().getTime(),true); <!--将请求发送到服务器--> xhr.send(null); <!--get请求方式--> }else if(obj.type == 'post' || obj.type == 'POST'){ <!--连接服务器--> xhr.open(obj.type,obj.url,true); <!--设置Http请求头--> xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); <!--将请求发送到服务器--> xhr.send(obj.data); <!--post请求方式--> } <!--等待服务器响应--> xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ <!--请求已完成--> if(xhr.status == 200){ <!--数据返回OK--> obj.success(xhr.responseText); }else{ obj.faided(xhr.status); } } } }
注:ajax请求顺序:
1,创建ajax对象:(XMLHttpRequest)/(ActiveXObject);
2,连接服务器;xhr.open(method,url,async),参数分别指(传递方式,地址,异步或同步)
3,将请求发送到服务器:xhr.send(param);
4,服务器响应情况:readyState属性可查看响应状态;
请求未初始化:0
服务器连接已建立:1
请求已接收:2
请求处理中:3
请求已完成:4
status: http请求的状态码;
请求成功:200;
网页被重定向到其他的URL:301;
文件未被修改,使用缓存资源:304;
找不到此网页(资源):404;
服务器内部错误:500;
更多状态码: http://www.runoob.com/http/http-status-codes.html
以上为封装函数代码以及请求顺序,谢谢!(web新手,欢迎指导)