Ajax技術的核心XMLHttpRequest對象

以下簡稱:XHR

幹嘛用的:

爲服務器發送請求和解析服務器響應提供了流暢的接口。能夠以異步的方式從服務器獲得更多信息,意味着用戶單擊後不用刷新頁面也可以取得新數據。也就是說,ajax技術中使用XHR對象取得新數據,再通過DOM將新數據插入頁面中。

用法:

var xhr=new XMLHttpRequest();
xhr.open(‘要發送的請求類型’,‘請求的url’,是否異步發送的布爾值);
//沒真發,就是啓動一個請求以備發送
xhr.send();//真發了

收服務器響應後,響應的數據會自動填充XHR對象的屬性,如下

responseText:作爲響應主體被返回的文本;
responseXML:如果響應的主體是’text/xml‘or’application/xml‘,這個屬性中將保存着響應數據的XML DOM文檔;
status:響應的http狀態。如:404,200
statusText:Http狀態的說明

var xhr=new XMLHttpRequest();
xhr.open(‘get’,‘/post.jsonl’,true);
xhr.send();
if((xhr.status>=200 && xhr.status<300)||xhr.status==304){
  alert(xhr.responseText);
}else{
 alert(xhr.status);
}

還有些xhr屬性,如:
readyState:表示請求/響應過程的活動階段,可取的值如下
0:未初始化。還沒調用open方法。
1:啓動。調用了open還沒send。
2:發送。調用了send,還沒收到響應。
3:接收。已經接收部分數據。
4:完成。接收完畢所有響應數據。
只要readyState一改變就觸發readystatechange事件。

var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
    if((xhr.status>=200 && xhr.status<300)||xhr.status==304){
         alert(xhr.responseText);
    }else{
        alert(xhr.status);
         }
}
} ;
xhr.open(‘get’,‘/post.jsonl’,true);
xhr.send();

Http頭部信息:

自定義http頭部信息,爲啥要設置這個的建議去看http圖解一書。

xhr.setRequestHeader("頭部字段", "頭部字段的值");
把這個放在open和send中間使用。
xhr.getResponseHeader("頭部字段"):得到相應的值。
xhr.getAllPesponseHeaders();
//得到一個包含所有頭部信息的長字符串。

get

最常見用於想服務器查詢某些信息。對於xhr來說,url末尾的查詢字符串必須經過正確的編碼纔行。
tips:所有名-值對兒都必須由&分開。
查詢字符串中每個參數的名稱和值都必須使用encodeURIComponent()進行編碼

xhr.open("get","example.php?name1=value1&name2=value2",true);

可以使用這個函數來幫助向現有url末尾添加查詢字符串參數

function addURLParam(url,name,value){
 url+=(url.indexOf("?")==-1"?":"&");
 url+=encodeURIComponent(name)+"="+encodeURIComponent(value);
return url;
}

下面結合實際例子來使用這個函數

function addURLParam(url,name,value){
 url+=(url.indexOf("?")==-1"?":"&");
 url+=encodeURIComponent(name)+"="+encodeURIComponent(value);
return url;
}
var url="example.php";
 url=addURLParam(url,"name","yourfather");
 url=addURLParam(url,"book","yourpornbook");
 xhr.open("get",url,false);

post

function submitData(){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
    if((xhr.status>=200 && xhr.status<300)||xhr.status==304){
         alert(xhr.responseText);
    }else{
        alert(xhr.status);
         }
 }
 }
};
xhr.open("post","example.php",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//表單提交時的內容類型
var form=document.getElementById('user-info');
xhr.send(serialize(form));
//而在XMLHttpRequest2中規定了
FormData對象
new 一個FormData對象後,xhr.send(new FormData(form));
這樣就不需要手動寫請求頭

跨域

除了ie定義了一個XDR(XDomainRequest)類型外,其他主流瀏覽器都可以直接用標準的XHR對象來實現跨域請求。

function createXHR()
{
    if (typeof XMLHttpRequest != "undefined")
    {
        return new XMLHttpRequest();
    } // end if
    else if (window.ActiveXObject)
    {
        var aVersions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0"];
        for (var i = 0; i < aVersions.length; ++i)
        {
            try
            {
                var oXHR = new ActiveXObject(aVersions[i]);
                return oXHR;
            } // end try
            catch (oError)
            {
                // do nothing
            } // end catch
            
        } // end for
        
    } // end else if
    
    throw new Error("XMLHttp object could not be created.")
    
} // end createXHR();

var xhr= createXHR();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
    if((xhr.status>=200 && xhr.status<300)||xhr.status==304){
         alert(xhr.responseText);
    }else{
        alert(xhr.status);
         }
 }
 };
 xhr.open("get","http://www.somewhere-else.com/page/",true);
 xhr.send();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章