ajax function encapsulation

Sometimes ajax is used in development, and it is impossible to go to ajax every time, so the ajax function is encapsulated. This article does not cover the basics of ajax. If you are interested, you can check my other article on how ajax works http://www.cnblogs.com/salmonlin/p/8962777.html

function ajax (method,url,data,success){ //Four parameters, method is the method, url is the path, data is the parameter sent in the background first, and success is the function called after
var xhr = null;
try{ //Process XMLHttpRequest Object compatibility
xhr = new XMLHttpRequest();
}catch(e){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if(method == 'get' && data){
url += '?' + data ;
}
xhr.open(method,url,true);
if(method == 'get'){
xhr.send();
}
else{
xhr.setRequestHeader("Content-type","application/x-www-form -urlencoded");
xhr.send(data);
}

xhr.onreadystatechange=function(){
if ( xhr.readyState == 4 ) {

if ( xhr.status == 200 ) {
success &&success(xhr.responseText);
}
else {
alert('Something went wrong, Err:' + xhr.status);
}
}
}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324972305&siteId=291194637