回归下原生js,网上看到的ajax封装,遂拿来改改,不知还有何弊端,望指出!
var ajaxhelper = { /*1.0 浏览器兼容的方式创建异步对象*/ makexhr: function () { //声明异步对象变量 var xmlhttp = false; //声明 扩展 名 var xmlhttpobj = [msxml2.xmlhttp.5.0, msxml2.xmlhttp.4.0, msxml2.xmlhttp.3.0, msxml2.xmlhttp, msxml.xmlhttp]; //判断浏览器是否支持 xmlhttprequest,如果支持,则是新式浏览器,可以直接创建 if (window.xmlhttprequest) { xmlhttp = new xmlhttprequest(); } //否则,只能循环遍历老式浏览器异步对象名,尝试创建,知道创建成功为止 else if (window.activexobject) { for (i = 0; i < xmlhttpobj.length; i++) { xmlhttp = new activexobject(xmlhttpobj[i]); if (xmlhttp) { break; } } } //判断 异步对象 是否创建 成功,如果 成功,则返回异步对象,否则返回false return xmlhttp ? xmlhttp : false; }, /*2.0 发送ajax请求*/ doajax: function (method, url, data, isayn, callback, type) { method = method.tolowercase(); //2.1创建异步对象 var xhr = this.makexhr(); //2.2设置请求参数(如果是get,则带url参数,如果不是,则不带) xhr.open(method, url + (method == get ? ? + data : ), isayn); //2.3根据请求谓词(get/post),添加不同的请求头 if (method == get) { xhr.setrequestheader(if-modified-since, 0); } else { xhr.setrequestheader(content-type, application/x-www-form-urlencoded); } //2.4设置回调函数 xhr.onreadystatechange = function () { //如果接受完毕 服务器发回的 响应报文 if (xhr.readystate == 4) { //判断状态码是否正常 if (xhr.status == 200) { if (type.tolowercase() == json) { var ret = {}; try { if (typeof json != undefined) { ret = json.parse(xhr.responsetext); } else { //ie8以下不支持json ret = new function(return + xhr.responsetext)(); } callback(ret); } catch (e) { console.log(e.message); callback(false); } } else { //直接返回文本 callback(xhr.responsetext); } } else { console.log(ajax status code: + xhr.status); callback(false); } } }; //2.5发送(如果是post,则传参数,否则不传) xhr.send(method != get ? data : null); }, /*3.0 直接发送post请求*/ dopost: function (url, data, isayn, callback, type) { this.doajax(post, url, data, isayn, callback, type); }, /*4.0 直接发送get请求*/ doget: function (url, data, isayn, callback, type) { this.doajax(get, url, data, isayn, callback, type); } };
假设一个需求,后端要求传入两个数字n1、n2,然后返回总和。
当其中一个参数为空或者不是数字时,返回:{status:0, msg:参数有误!}
当正确的时候,返回:{status:1, sum://n1加n2的和}
后端的代码就不贴出来了。
前端调用:
document.getelementbyid(btnsubmit).onclick = function () { ajaxhelper.dopost(后端url, n1=10&n2=25, true, function (ret) { if (!ret) { return; } if (ret.status != 1) { alert(ret.msg); return; } var n = ret.sum; var s = ret.status; }, json); };
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
ajax和javascript使用的区别
ajax与浏览器缓存的使用详解
以上就是怎样实现原生ajax封装的详细内容。