封装get和post函数

 fn("post","1.post.php","username=sunzian&age=20");

    function fn(a,b,c) {
        if(window.XMLHttpRequest){
            var xhr=new XMLHttpRequest();
        }
        else{
            var xhr=new ActiveXObject(Microsoft.XMLHTTP)
        }
        if(a=="get"){
            xhr.open("get",b+"?"+c,true);
            xhr.send()
        }
        else if(a=="post"){
            xhr.open("post",b,true);
            xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
            var data=c;
            xhr.send(data);
        }
        xhr.onreadystatechange=function () {
            if(xhr.readyState==4 & xhr.status==200) {
                var str = xhr.responseText;
                var json = JSON.parse(str);
                document.write(json);
//                fun(str);
            }
            else if(xhr.status==404){
                document.write("404")
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/moonlight201868/article/details/80978637