ajax 原生 xhr 對象

事件
    onreadystatechange
    
    xhr.open("get","example.php", false);
    xhr.send(null)
    send()方法接收一個參數,即要做爲請求主體發送的數據。調用send()方法後,請求被分派到服務器
    若是是GET方法,send()方法無參數,或參數爲null;若是是POST方法,send()方法的參數爲要發送的數據


    響應以前
    readyState
    0(UNSENT):未初始化。還沒有調用open()方法
    1(OPENED):啓動。已經調用open()方法,但還沒有調用send()方法
    2(HEADERS_RECEIVED):發送。己經調用send()方法,且接收到頭信息

    3(LOADING):接收。已經接收到部分響應主體信息
    4(DONE):完成。已經接收到所有響應數據,並且已經能夠在客戶端使用了


    responseText: 做爲響應主體被返回的文本(文本形式)
    status: HTTP狀態碼(數字形式)
    200 ok 304 不ok
    404,500

php

 

function myAjax(method,url,data,fn){
    var xhr;

    // console.log(XMLHttpRequest);

    if(window.XMLHttpRequest){
        xhr = new XMLHttpRequest();
    }else{
        xhr = new ActiveXObject('Microsoft.XMLHTTP');
    }

    xhr.onreadystatechange = function(){
        if(xhr.readyState =='4'){
            if(xhr.status == '200'){
                // alert(xhr.responseText);
                fn(xhr.responseText);
            }    
                    
        }

    }
     //發送請求
    xhr.open(method,url,true);
    (method == 'get')?xhr.send();xhr.send(data):
    
    // console.log(xhr);

}
相關文章
相關標籤/搜索