美文网首页
封装ajax

封装ajax

作者: 2点半 | 来源:发表于2017-07-03 16:21 被阅读0次
    封装方法
      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';
            }
        });
    }
    
    
    

    相关文章

      网友评论

          本文标题:封装ajax

          本文链接:https://www.haomeiwen.com/subject/rcczcxtx.html