ajax一

最简单版的ajax

get版本

        var xhr = null //创建对象
        if(window.XMLHttpRequest){
            xhr = new XMLHttpRequest() //重新赋值
        }else{
            xhr = new ActiveXObject('Microsoft.XMLHTTP') //重新赋值(鉴别ie6)
        }
        xhr.open('get','url?xxx'+xxx,true) //准备发送
        xhr.send(null) //执行发送
        xhr.onreadystatechange = function (){ //回调函数
            if(xhr.readyState == 4){
                if(xhr.status == 200){
                    //xhr.responseXML
                    var result = xhr.responseText
                    console.log(result)
                }
            }
        }

post版本

        var xhr = null //创建对象
        if(window.XMLHttpRequest){
            xhr = new XMLHttpRequest() //重新赋值
        }else{
            xhr = new ActiveXObject('Microsoft.XMLHTTP') //重新赋值(鉴别ie6)
        }
        xhr.open('post','url',true) //准备发送
        xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded')
        var param = 'xxx'+xxx
        xhr.send(param) //执行发送
        xhr.onreadystatechange = function (){ //回调函数
            if(xhr.readyState == 4){
                if(xhr.status == 200){
                    //xhr.responseXML
                    var result = xhr.responseText
                    console.log(result)
                }
            }
        }

去加油吧少年!

原文地址:https://www.cnblogs.com/xufeng1994/p/10424692.html