原生js實現ajax

手寫ajax

function get(url,callback){

    var xhr = new XMLHttpRequest(); 

    xhr.open('GET',url,true)

    xhr.onreadystatechange = function(){

        if(xhr.readyState === 4 && xhr.status == 200 || xhr.status == 304){
            callback(response)
        }
    }

    xhr.send()
}

function post(url,data,callback){
    var xhr = new XMLHttpRequest()
    
    xhr.open('POST',url,true)
    
    xhr.setRequestHeader('Content-Type':"application/x-www-form-urlencoded")
    
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4 && xhr.status === 200 || xhr.status === 304){
            callback(response)
        }
    }
    xhr.send()
}複製代碼
相關文章
相關標籤/搜索