首页 > 代码库 > 手动封装js原生XMLHttprequest异步请求
手动封装js原生XMLHttprequest异步请求
Code (var name in paramters) { //将数组中的数据以=拼接后再添加到data数组中 [name=aa,age=11] var _regesp = /%20/g; //空格的正则表达式 var _value = http://www.mamicode.com/paramters[name].toString(); //获取值 data.push(encodeURIComponent(name).replace(_regesp, ‘+‘) + "=" + encodeURIComponent(_value).replace(_regesp, ‘+‘)); } //以&将数组元素拼接后返回 如:name=aa&age=11 return data.join("&"); }, _regCallback:function(xhr){ var _this=this; xhr.onreadystatechange = function(){ if (xhr.readyState == 4) { if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 300) { _this.options.success(_this._getResponseData(xhr), xhr.statusText); } else { _this.options.failure(xhr.status, xhr.statusText); } } } }, _getResponseData:function(xhr){ var responseType = xhr.getResponseHeader("Content-Type"); switch (responseType) { case ‘text/xml‘: return xhr.responseXML; case ‘text/json‘: case ‘text/javascript‘: case ‘application/javascript‘: case ‘application/x-javascript‘: return eval(‘(‘ + xhr.responseText + ‘)‘); default: return xhr.responseText; }; }, _init:function(options){ this.options=options; if(this.options.url=="") return; this.xhr = this._createXhr();//创建异步对象 this._regCallback(this.xhr);//注册回调事件 //根据请求类型,发送异步请求 if(this.options.type.toLowerCase()=="post"){ this._post(this.xhr); } else{ this._get(this.xhr); } }, _post:function(xhr){ this.xhr=xhr; this.data=http://www.mamicode.com/this._encodeData(this.options.data); this.url=this.options.url+"?d=" + parseInt(Math.random()*100+1,10); this.asyn=!!this.options.isAsyn; xhr.open("POST", this.url, this.asyn); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(this.data); }, _get:function(xhr){ this.xhr=xhr; this.data=http://www.mamicode.com/this._encodeData(this.options.data); this.url=this.options.url+‘?‘ + this.data + ‘&d=‘ + parseInt(Math.random()*100+1,10); this.asyn=!!this.options.isAsyn; xhr.open(‘GET‘, this.url, this.asyn); xhr.send(null); } }); this._init(this.options); }; return HttpAjax;})(window);
Code
Code
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。