使用原生JS封装Ajax

时间:2022-09-23 21:55:14

使用原生 的JS封装 Ajax,实现 仿JQuery的Ajax,post,get三种异步请求方式:

var MAjax = {
//根据浏览器创建异步对象
createXhr: function () {
//经测试:IE7.0及以上版本的IE,两种异步创建的两种方式都支持
//如果XMLHttpRequest存在,则是IE7.0及其它内核,则直接创建异步对象(!==非全等于, === 全等于)
if (typeof XMLHttpRequest !== 'undefined') { //相当!(typeof XMLHttpRequest === 'undefined')
return new XMLHttpRequest();
}
//如果ActiveObject存在,是IE7.0或以下IE内核,判断其版本,并创建相应的异步对象
else if (typeof ActiveXObject !== 'undefined') {
//如果ActiveObject对象的参数类型不是string类型,则判断ie版本并创建异步对象
var versions = ['MSXML2.XMLHttp.6.0', 'MSXML2.XMLHttp.3.0', 'MSXML2.XMLHttp'];
for (var i = 0, len = versions.length; i < len; i++) {
try {
//在此创建出错的话,就跳到catch中,否则执行下一句,返回创建成功的对象
var xhr = new ActiveXObject(versions[i]);
//给当前窗体对象添加一个属性用于判断 是否创建成功了
this.IsCreateOk = versions[i];
return xhr;
}
catch (e) { }
}
if (typeof this.IsCreateOk === 'undefined') {
alert(
"您的浏览器版本过低,无法创建异步对象,请升级您的浏览器!");
}
}

},

//将请求参数编码后拼接成url参数:例 name=aa&age=11 传入参数:{name:aa,age:11}
encodeData: function (paramters) {
var data = [];
for (var name in paramters) {
//将数组中的数据以=拼接后再添加到data数组中 [name=aa,age=11]
var _regesp = /%20/g; //空格的正则表达式
var _value = paramters[name].toString(); //获取值
data.push(encodeURIComponent(name).replace(_regesp, '+') + "=" + encodeURIComponent(_value).replace(_regesp, '+'));
}
//以&将数组元素拼接后返回 如:name=aa&age=11
return data.join("&");
},

//根据响应头类型,获取相对应类型的数据
responseData: function (request) {
var responseType = request.getResponseHeader("Content-Type");
switch (responseType) {
case 'text/xml':
return request.responseXML;
case 'text/json':
case 'text/javascript':
case 'application/javascript':
case 'application/x-javascript':
return eval('(' + request.responseText + ')');
default:
return request.responseText;
}
},

//ajax请求
ajax: function (options) {
//method, url, data, success,failure, asyn
var fn = function () { };
options.method
= options.method.toUpperCase();
options.url
= options.url;
options.data
= this.encodeData(options.data);
options.success
= options.success || fn();
options.failure
= options.failure || fn();
options.asyn
= typeof (options.asyn) == 'undefined' ? true : options.asyn;

var xhr = this.createXhr();


//注册回调函数(每当异步请求状态0-4改变的时候,就调用此函数)【一定要在Open之前注册】
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {//判断 请求是否完成,响应是否就绪
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 300) {//判断返回的响应状态码
options.success(MSF.responseData(xhr), xhr.statusText);
}
else {
options.failure(xhr.status, xhr.statusText);
}
}
}

//判断请求类型,并发送请求和请求参数
switch (options.method) {
case 'POST':
xhr.open(options.method, options.url, options.asyn);
xhr.setRequestHeader(
'Content-Type', 'application/x-www-form-urlencoded'); //【在send之前设置请求头】
xhr.send(options.data);
break;
default:
options.url
= options.url + '?' + options.data + '&d=' + Math.random(0, 99); //get请求,给url添加参数
xhr.open(options.method, options.url, options.asyn);
xhr.send(
null);
break;
}
},

//get请求
get: function (url, data, callback) {
var fn = function () { };
callback
= callback || fn();
this.url = url + '?' + this.encodeData(data) + '&d=' + Math.random(0, 99);

//创建异步对象
var xhr = this.createXhr();

//注册回调函数(每当异步请求状态0-4改变的时候,就调用此函数)【一定要在Open之前注册】
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {//判断 请求是否完成,响应是否就绪
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 300) {//判断返回的响应状态码
callback(MSF.responseData(xhr), xhr.statusText);
}
else {
callback(xhr.status, xhr.statusText);
}
}
}

//开始异步
xhr.open('GET', this.url, true);
xhr.send(
null);
},

//post请求
post: function (url, data, callback) {
this.url = url + "?d=" + Math.random(0, 99);
callback
= callback || function () { };
this.data = this.encodeData(data);

var xhr = this.createXhr();

xhr.onreadystatechange
= function () {
if (xhr.readyState == 4) {//判断 请求是否完成,响应是否就绪
if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 300) {//判断返回的响应状态码
callback(MSF.responseData(xhr), xhr.statusText);
}
else {
callback(xhr.status, xhr.statusText);
}
}
}

xhr.open(
"POST", this.url, true);
xhr.setRequestHeader(
"Content-Type", "application/x-www-form-urlencoded");
xhr.send(
this.data);
}
};

使用实例:

//调用:
MAjax.ajax({
method:
"get",
url:
"GetPaht_Test.aspx",
data: {
"name": "jack", "age": 15 },
success:
function (data,state) { alert(data+"----"+state); },
failure:
function () { alert("请求失败了") }
});

MAjax.get(
"GetPaht_Test.aspx",
{
"name": "jack", "age": 15 },
function (data, state) { alert(data + "----" + state) }
);

MAjax.post(
"GetPaht_Test.aspx",
{
"name": "jack", "age": 15 },
function (data, state) { alert(data + "----" + state) }
);