jquery ajax 调用,如何在没有jQuery的情况下进行AJAX调用?

匿名用户

使用下面的代码段,您可以非常容易地完成类似的事情,如下所示:ajax.get('/test.php', {foo: 'bar'}, function() {});

下面是一个片段:var ajax = {};

ajax.x = function () {

if (typeof XMLHttpRequest !== 'undefined') {

return new XMLHttpRequest();

}

var versions = [

"MSXML2.XmlHttp.6.0",

"MSXML2.XmlHttp.5.0",

"MSXML2.XmlHttp.4.0",

"MSXML2.XmlHttp.3.0",

"MSXML2.XmlHttp.2.0",

"Microsoft.XmlHttp"

];

var xhr;

for (var i = 0; i < versions.length; i++) {

try {

xhr = new ActiveXObject(versions[i]);

break;

} catch (e) {

}

}

return xhr;

};

ajax.send = function (url, callback, method, data, async) {

if (async === undefined) {

async = true;

}

var x = ajax.x();

x.open(method, url, async);

x.onreadystatechange = function () {

if (x.readyState == 4) {

callback(x.responseText)

}

};

if (method == 'POST') {

x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

}

x.send(data)

};

ajax.get = function (url, data, callback, async) {

var query = [];

for (var key in data) {

query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));

}

ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)

};

ajax.post = function (url, data, callback, async) {

var query = [];

for (var key in data) {

query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));

}

ajax.send(url, callback, 'POST', query.join('&'), async)

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值