欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

原生JS写Ajax的请求函数功能

程序员文章站 2022-10-30 21:13:09
一般我们写网页的时候,如果用到 ajax 请求服务器,都是使用 jquery 等已经封装好的库来调用,比较简单。 但是一般这些库的功能很多,引入了太多我们用不到的东西,如...

一般我们写网页的时候,如果用到 ajax 请求服务器,都是使用 jquery 等已经封装好的库来调用,比较简单。

但是一般这些库的功能很多,引入了太多我们用不到的东西,如果我们需要写一个功能单一,简单的页面,完全用不到引用如此庞大的库文件。

我们可以简单实现一个自己的 ajax 请求功能,具体的代码如下:

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, method, data, success,fail,async) {
 if (async === undefined) {
 async = true;
 }
 var x = ajax.x();
 x.open(method, url, async);
 x.onreadystatechange = function () {
 if (x.readystate == 4) {
 var status = x.status;
 if (status >= 200 && status < 300) {
 success && success(x.responsetext,x.responsexml)
 } else {
 fail && fail(status);
 }
 }
 };
 if (method == 'post') {
 x.setrequestheader('content-type', 'application/x-www-form-urlencoded');
 }
 x.send(data)
};
ajax.get = function (url, data, callback, fail, async) {
 var query = [];
 for (var key in data) {
 query.push(encodeuricomponent(key) + '=' + encodeuricomponent(data[key]));
 }
 ajax.send(url + (query.length ? '?' + query.join('&') : ''), 'get', null, callback, fail, async)
};
ajax.post = function (url, data, callback, fail, async) {
 var query = [];
 for (var key in data) {
 query.push(encodeuricomponent(key) + '=' + encodeuricomponent(data[key]));
 }
 ajax.send(url,'post', query.join('&'), callback, fail, async)
};

使用方法: get

ajax.get('/test.php', {foo: 'bar'}, function(response,xml) {
 //success
},
function(status){
 //fail
});
post
ajax.post('/test.php', {foo: 'bar'}, function(response,xml) {
 //succcess
},function(status){
 //fail
});

这里需要注意一个问题,如果我们想要发送类似

var sendcmd = "?op_code=" + code + "&op_cmd=" + cmd;
ajax.post('/control' + sendcmd,'',function(response,xml) {
 console.log('success');
},
function(status){
 console.log('failed:' + status);
});

总结

以上所述是小编给大家介绍的原生js写ajax的请求函数功能,希望对大家有所帮助