封装方法
function ajax(method,url,data,success){//方法,路径,参数,函数
var xhr=null;
try{
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.reponseText)
}else{
alert("err"+xhr.status)
}
}
}
}
调用示例
btn.onblur = function() {
ajax('get', 'index.php', 'm=index&a=verifyUserName&username=' + this.value, function(data) {
var d = JSON.parse(data);
oVerifyUserNameMsg.innerHTML = d.message;
if (d.code) {
oVerifyUserNameMsg.style.color = 'red';
} else {
oVerifyUserNameMsg.style.color = 'green';
}
});
}