Home >Web Front-end >JS Tutorial >The beginning of front-end development---based on object-oriented Ajax class_js object-oriented

The beginning of front-end development---based on object-oriented Ajax class_js object-oriented

WBOY
WBOYOriginal
2016-05-16 18:19:221188browse

Let’s look at the calling method first:

Copy code The code is as follows:

ajax.request( "ajax.html",{v:Math.random(),num:1},function(data){
//do something
},'get');



The method is like jquery. . . I still find it more convenient to call it this way. . .
Copy code The code is as follows:

var ajax = {
//Xmlhttprequest class
Xmlhttprequest :function() {
this.xhr =false;
},
//External call interface
request : function(url,data,callback,type) {
/ /Create an Xmlhttprequest object each time so that ajax calls do not affect each other
var xhr = new this.Xmlhttprequest();
xhr.request(url,data,callback,type);
}
}
//Convert the json data format {num:1,t:'a'} to the string format num=1&t=a
var json2str = function(data){
var _data = [];

for(var name in data) {
_data.push(name "=" data[name]);
}
return _data.join( '&');
}
//Methods to extend the Xmlhttprequest class
ajax. >if(window.XMLHttpRequest) {
return new XMLHttpRequest();
}
else {
var a = ["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP. 5.0","Msxml2.XMLHTTP.4.0","Msxml2.XMLHTTP.3.0"];
for (var i=0,l=a.length;itry{
return new ActiveXObject(a[i]);
}catch(e){};
}
}
},
//Callback function
fnCallback: function(callback ){

if(this.xhr.readyState === 4 && this.xhr.status === 200) {
callback?callback(this.xhr.responseText):void(0);
}
},
//ajax request
request: function(url, data, callback, type){

var that = this;
var ispost = type ==='post'?true:false;

ispost?url:url = '?' json2str(data);

this.xhr = this.createXmlHttpRequest();

this.xhr.open(type,url,true);
ispost?this.xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"):'';
this.xhr.onreadystatechange = function(){that.fnCallback(callback);};
this.xhr.send(ispost?json2str(data):null);
}
}



There must be some shortcomings in this category, please feel free to give it a try! Everyone has their own customary usage, the most important thing is to use it appropriately!
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn