ajax方法封装code:
ZIP_Ajax.prototype={ request:function(url options){ this.options=options; if(options.method=="jsonp"){//跨域请求 return this.jsonp(); } var httpRequest=this.http(); options=Object.extend({method: 'get', async: true},options||{}); if(options.method=="get"){ url+=(url.indexOf('?')==-1?'?':'&')+options.data; options.data=null; } httpRequest.open(options.method,url,options.async); if (options.method == 'post') { httpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8'); } httpRequest.onreadystatechange = this._onStateChange.bind(this, httpRequest, url, options); httpRequest.send(options.data || null);//get请求情况下data为null return httpRequest; }, jsonp:function(){ jsonp_str = 'jsonp_' + new Date().getTime(); eval(jsonp_str + ' = ' + this.options.callback + ';'); this.options.url += '?callback=' + jsonp_str; for(var i in this.options.data) { this.options.url += '&' + i + '=' + this.options.data[i]; } var doc_head = document.getElementsByTagName("head")[0], doc_js = document.createElement("script"), doc_js.src = this.options.url; doc_js.onload = doc_js.onreadystatechange = function(){ if (!this.readyState || this.readyState == "loaded" || this.readyState == "complete"){ //清除JS doc_head.removeChild(doc_js); } } doc_head.appendChild(doc_js); }, http:function(){//判断是否支持xmlHttp if(window.XMLHttpRequest){ return new XMLHttpRequest(); } else{ try{ return new ActiveXObject('Msxml2.XMLHTTP') } catch(e){ try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) { return false; } } } }, _onStateChange:function(http,url,options){ if(http.readyState==4){ http.onreadystatechange=function(){};//重置事件为空 var s=http.status; if(typeof(s)=='number'&&s>200&&s<300){ if(typeof(options.success)!='function')return; var format=http; if(typeof(options.format)=='string'){//判断请求数据格式 switch(options.format){ case 'text': format=http.responseText; break; case 'json': try{ format=eval('('+http.responseText+')'); } catch (e) { if (window.console && console.error) console.error(e); } break; case 'xml': format=http.responseXML; break; } } options.success(format);//成功回调 } else {//请求出问题后处理 if (window.closed) return; if (typeof (options.failure) == 'function') { var error = { status: http.status, statusText: http.statusText } // 判断是否是网络断线或者根本就请求不到服务器 if (http.readyState == 4 && (http.status == 0 || http.status == 12030)) { // 是 error.status = -1; } options.failure(error); } } } } };使用方法:
ajax调用举例:
var myAjax=new ZIP_Ajax("http://www.a.com/you.php",{ method:"get", data:"key=123456&name=yuchao", format:"json", success:function(data){ ...... } }) 跨域请求调用举例: var jsonp=new ZIP_Ajax("http://www.a.com/you.php",{ method:"jsonp", data:{key:"123456",name:"yuchao"}, callback:function(data){ ...... } })您可能感兴趣的文章: