原生ajax方法,原生JavaScript写的Ajax方法

/* 示例:

ajax({

//async: true, // 默认是 true(异步)

//headers: {}, // 额外的"{键:值}"对映射到请求一起发送,仅限 POST

//type: "GET", // 默认是 GET

//dataType: "json", // 默认是 json

url: "./TestXHR.php",

data: { name: "super", age: 20 },

success: function (response, xml) {

// console.log(status);

},

error: function (status) {

console.log(status);

console.log('ajax error');

}

});

*/

function ajax(o) {

if (typeof(o) != 'object' || typeof(o.url) != 'string') return;

o.type = (o.type || 'GET').toUpperCase();

o.dataType = (o.dataType || 'json').toLowerCase();

o.headers = o.headers || {};

var t = typeof(o.async);

o.a = t == 'undefined' ? true: t == 'string' ? o.async.toLowerCase() != 'false': Boolean(o.async);

var params = formatParams(o.data);

var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

xhr.onreadystatechange = function() {

if (xhr.readyState != 4) return;

var status = xhr.status;

if (status >= 200 && status < 300) {

if (!o.success) return;

if (o.dataType != 'json') o.success(xhr.responseText, xhr.responseXML);

else try {

o.success(JSON.parse(xhr.responseText), xhr.responseXML)

} catch(e) {

o.success(xhr.responseText, xhr.responseXML)

}

} else if (o.error) o.error(status)

};

if (o.type == "GET") {

xhr.open("GET", o.url + "?" + params, o.a);

xhr.send(null)

} else if (o.type == "POST") {

xhr.open("POST", o.url, o.a);

for (var k in o.headers) {

xhr.setRequestHeader('"' + k + '"', '"' + o.headers[k] + '"');

k.toLowerCase() == 'content-type' && (o.c=true);

}

typeof(o.c)=='undefined' && xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.send(params)

}

}

function formatParams(data) {

var arr = [];

for (var name in data) {

arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]))

}

arr.push(("v=" + Math.random()).replace(".", ""));

return arr.join("&")

}

下面是压缩版

function ajax(o){if(typeof(o)!='object'||typeof(o.url)!='string')return;o.type=(o.type||'GET').toUpperCase();o.dataType=(o.dataType||'json').toLowerCase();o.headers=o.headers||{};var t=typeof(o.async);o.a=t=='undefined'?true:t=='string'?o.async.toLowerCase()!='false':Boolean(o.async);var params=formatParams(o.data);var xhr=XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');xhr.onreadystatechange=function(){if(xhr.readyState!=4)return;var status=xhr.status;if(status>=200&&status<300){if(!o.success)return;if(o.dataType!='json')o.success(xhr.responseText,xhr.responseXML);else try{o.success(JSON.parse(xhr.responseText),xhr.responseXML)}catch(e){o.success(xhr.responseText,xhr.responseXML)}}else if(o.error)o.error(status)};if(o.type=="GET"){xhr.open("GET",o.url+"?"+params,o.a);xhr.send(null)}else if(o.type=="POST"){xhr.open("POST",o.url,o.a);for(var k in o.headers){xhr.setRequestHeader('"'+k+'"','"'+o.headers[k]+'"');k.toLowerCase()=='content-type'&&(o.c=true)}typeof(o.c)=='undefined'&&xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr.send(params)}}function formatParams(data){var arr=[];for(var name in data){arr.push(encodeURIComponent(name)+"="+encodeURIComponent(data[name]))}arr.push(("v="+Math.random()).replace(".",""));return arr.join("&")}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值