原生JS写Ajax的请求函数功能
一般我们写网页的时候,如果用到 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); });
总结
相关推荐
lyqdanang 2020-08-16
坚持着执着 2020-06-16
坚持着执着 2020-07-16
坚持着执着 2020-06-14
TONIYH 2020-06-05
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19
83510998 2020-07-18
jiaguoquan00 2020-07-07