function ajax(method, url, data, success){
/*1.创建一个ajax对象
ie6以下new ActiveXObject('Microsoft.XMLHTTP')*/
var xhr;
if( window.XMLHttpRequest ){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject('Microsoft.XMLHTTP');//ie6
}
//请求
/*
open方法
参数
1.打开方式
2.地址
3.是否异步
异步:非阻塞 前面的代码不会影响后面代码的执行
同步:阻塞 前面的代码会影响后面代码的执行
*/
/*send();
提交,发送请求*/
if( method == 'get' && data ){
url += '?'+data;
xhr.open(method, url, true);
xhr.send();
}else if( method == 'post' ){
xhr.open(method, url, true);
xhr.setRequestHeader('content-Type', 'application/x-www-form-urlencoded');// 设置请求头
xhr.send(data);
}
//响应
//等待服务器返回内容
/*
readyState : ajax工作状态
responseText : ajax请求返回的内容就被存放到这个属性下面
on readystate change : 当readyState改变的时候触发
status : 服务器状态,http状态码
*/
xhr.onreadystatechange = function(){
if( xhr.readyState == 4 ){
if( xhr.status == 200 ){
// alert(xhr.responseText);
success && success(xhr.responseText);
}else{
alert('出错了,Err:' + xhr.status);
}
}
}
}
ajax封装
最新推荐文章于 2023-09-20 10:27:08 发布