JavaScript之Ajax Util
ajax(即:Asynchronous JavaScript and XML(异步的 JavaScript 和 XML))经常在用,却经常忽略了底层的实现机制,今日写个小工具,大家也可拿去使用,如果写博客时需要引用时,请显著地注明出处,以尊重劳动成果,谢谢~
声明:本文仅讲述关于:JavaScript的ajax工具类设计、ajax规范设计者开放了哪些接口、以及ajax使用Demo。
零、推荐文献
[1] 轻量级AJAX库-搜狗实验室ajax.js
[2] 跨域问题小结
一、Chrome控制台网络调试小工具[方便、快捷、易用]
var xml = new XMLHttpRequest(); xml.withCredentials = true; // 开启Cookie,启用会话机制 var method = 'GET'; var url = "https://10.0.8.234/bms/static/pages/css/email.css?ver=20140102"; xml.open(method, url, true); xml.setRequestHeader("Content-type","application/json;charset=UTF-8"); // application/x-www-form-urlencoded //xml.setRequestHeader("referer","https://10.0.8.234:18199/bms/");//[会报错: Refused to set unsafe header "referer"] 为了安全,跨域XHR对象有一些限制: 不能使用 setRequestHeader() 设置自定义头部 不能发送和接收 cookie 调用 getAllResponseHeaders() 方法总会返回空字符串 //xml.send(); //xml.send(JSON.stringify( //JSON单条记录 //{ flowId: "1105", areaId: "530000", departmentId : "1350", loginName :"chenguoyong", userName :"陈国勇", userPhone: "18600000000", idCard: "", email: "" } //); xml.send('[' + JSON.stringify( //JSON数组 - 形式1 { flowId: "1105", areaId: "530000", departmentId : "1350", loginName :"chenguoyong", userName :"陈国勇", userPhone: "18600000000", idCard: "", email: "" } //,flowId: "1105", areaId: "530000", departmentId : "1350", loginName :"chenguoyong", userName :"陈国勇", userPhone: "18600000000", idCard: "", email: "" } ) + ']'); xml.send( JSON.stringify( [ //JSON数组 - 形式2 { flowId: "1105", areaId: "530000", departmentId : "1350", loginName :"chenguoyong", userName :"陈国勇", userPhone: "18600000000", idCard: "", email: "" } ,flowId: "1105", areaId: "530000", departmentId : "1350", loginName :"chenguoyong", userName :"陈国勇", userPhone: "18600000000", idCard: "", email: "" } ]) );
//动态引入css
new_element=document.createElement("link");
new_element.setAttribute("rel","stylesheet");
new_element.setAttribute("type","text/css");
new_element.setAttribute("referrerpolicy","no-referrer-when-downgrade");
new_element.setAttribute("href","https://10.0.8.234/bms/static/pages/css/three-plugin.css?ver=20140102");
document.body.appendChild(new_element);
But,注意一个问题:不同的ajax请求对象,如何保持会话Session/Cookie的问题
二、Ajax Util工具类设计
文末处,附属个人的一些笔记的截图(确实值得一阅)。如有不妥之处,还请大家指正,共同进步~
/** * Ajax Util * * @Author JohnnyZen * @DateTime 2017-11-22 * @copyright [johnny.weily] * @license [license] * @version [version] * @link http://www.johnnyzen.cn/ * @required itemX * * @param option { url[,method][,data][,async][,dataType]} * * @method 设置option,初始化ajax * @method complete:请求完成时运行的函数(在请求成功或失败之后均调用,即在success和error函数之后) * complete:function(responseText,status,event){} * complete:function(xhr,status){} * @method success:当请求成功时运行的函数 * success:function(responseText,status,event){} * success:function(response,status,xhr){} * @method error:请求出错时候的函数 * error:function(xhr,status,error){} * * @notice xhr 用于创建 XMLHttpRequest 对象的函数 * @notice event.target.readyState的各值意义 * XMLHttpRequest.DONE 4 响应完成或已失败 XMLHttpRequest.LOADING 3 已收到服务器响应 XMLHttpRequest.HEADERS_RECEIVED 2 已收到服务器响应的标头 XMLHttpRequest.OPEND 1 已调用open方法 XMLHttpRequest.UNSENT 0 已创建XMLHttpRequest对象 */ var Ajax = function(option){ this.option = { url: null, type: option.type == undefined ? "GET" : option.type, async: option.async == undefined ? true : option.async, data: option.data == undefined ? null : option.data, contentType: option.contentType == undefined ? option.contentType : "application/x-www-form-urlencoded; charset=UTF-8", complete: typeof(option.complete) == 'function' ? option.complete : this.defaultCompleteHandle, success: typeof(option.success) == 'function' ? option.success : this.defaultSuccessHandle, error:typeof(option.error) == 'function' ? option.error : this.defaultErrorHandle }, this.createAjaxRequest = function(){ var AjaxRequest = null;// 缓存XHR对象便于 Ajax 使用 try { // Opera 8.0+, Firefox, Safari AjaxRequest = new XMLHttpRequest(); } catch (e) { // Internet Explorer Browsers try { AjaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { AjaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { // 错误处理 throw new Error("Your browser broke!"); return false; } } } return AjaxRequest; }, this.defaultCompleteHandle = function(responseText,status,event){ console.log("[Ajax#defaultCompleteHandle] responseText:", event.target.responseText); //test console.log("[Ajax#defaultCompleteHandle] status:", event.target.status); //test }, this.defaultSuccessHandle = function(responseText,status,event){ console.log("[Ajax#defaultSuccessHandle] responseText:", event.target.responseText); //test console.log("[Ajax#defaultSuccessHandle] status:", event.target.status); //test }, this.defaultErrorHandle = function(event){ console.error("defaultErrorHandle:", "ajax request failed!"); }, (function(){ var AjaxRoot = this;//保存当前调用的根对象 var AjaxRequest = AjaxRoot.createAjaxRequest(); try{ AjaxRequest.onreadystatechange = function(event){ // console.log("option.log:",AjaxRoot.option.log);//test if( event.target.readyState == XMLHttpRequest.DONE){// 4 响应完成或已失败 console.log('AjaxRoot.option.complete', AjaxRoot.option.complete); AjaxRoot.option.complete(event.target.responseText,event.target.status,event); } else if(event.target.readyState == XMLHttpRequest.LOADING){// 3 已收到服务器响应 AjaxRoot.option.success(event.target.responseText,event.target.status,event); } } AjaxRequest.open(AjaxRoot.option.type, AjaxRoot.option.url, AjaxRoot.option.async); //ajax.open(option.method,option.url,[是否异步请求,默认为true:true],[user],[password]); console.log('AjaxRoot.option.data',AjaxRoot.option.data);//test AjaxRequest.send(AjaxRoot.option.data); }catch(e){ console.error(e); AjaxRoot.option.error(); return false; } })(); } //Ajax Util demo var option = { type:"GET", url:"http://apis.baidu.com/beijingprismcubetechnology/qmpapi/qmpproduct", async:true,//是否异步 dataType:"json", data:"hello", complete:function(responseText,status,event){ console.log("complete:",responseText); } } Ajax(option);
三、Ajax规范设计者们所提供的接口和一些常见问题的解决方案

本文链接: https://www.cnblogs.com/johnnyzen
关于博文:评论和私信会在第一时间回复,或直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
日常交流:大数据与软件开发-QQ交流群: 774386015 【入群二维码】参见左下角。您的支持、鼓励是博主技术写作的重要动力!