天天看點

Ajax基礎

1 概要

異步JavaScript和XML(Asynchronous Javascript And XML,Ajax)就是使用js來收發來自web伺服器的資料,且無需重載整個頁面的技術。

注 :xml是浏覽器和伺服器彼此通信的格式。

2 XMLHttpRequest 對象

XMLHttpRequest 是浏覽器的内置對象

2.1 基礎

2.1.1 建立 XMLHttpRequest 對象
//可用于連接配接、請求和接受伺服器中的資料
var request = new XMLHttpRequest(); 
           
2.1.2 XMLHttpRequest 對象主要方法

初始化XMLHttpRequest 對象

request.open("GET",url,async);
//參數一:表示請求類型的字元串,"GET"/"POST"
//參數二:請求目标的url
//參數三:表示是否以異步模式發出,true為異步(預設值,常用),false為同步
           

發送請求

request.send(null);
//send()方法必須接受一個參數,表示要發送的資料,也可以是null
           

用于設定請求頭

setRequestHeader(header,value)   
# header:請求頭的key
# value:請求頭的value
           

擷取所有響應頭

getAllResponseHeaders()
#傳回值:所有響應頭資料
           

擷取響應頭指定的header的值

getResponseHeader(header)
#header:響應頭的key(字元串類型)
#傳回值:響應頭中指定的header對應的值
           

終止請求

abort()
           
2.1.3 XMLHttpRequest 對象主要屬性
Number : readyState      每個值表示生存期中的特定狀态。eg:0,1,2,3,4
Function : onreadystatechange         當readyState的值改變時自動觸發執行其對應的函數(回調函數)
String : responseText         伺服器傳回的資料(字元串類型)
XmlDocument : responseXML        伺服器傳回的資料(xml對象)
Number : status         狀态嗎 eg:200,400
String : statusText        狀态文本(字元串) eg:OK,NotFound
           
2.1.4 get/post請求簡單實作
<script>
    function SubmitForm() {
        var xhr = new XMLHttpRequest();
        xhr.open("GET", "/login", true);
        xhr.onreadystatechange = func;
        xhr.send()
        function func() {
            if (xhr.readyState == 4) {
                console.log(xhr.responseText);
            }
        }
    }
</script>
           
<script>
    function SubmitForm() {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/login", true);
        xhr.onreadystatechange = func;
        //在使用post送出資料時要設定請求頭
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
        xhr.send()
        function func() {
            if (xhr.readyState == 4) {
                console.log(xhr.responseText);
            }
        }
    }
</script>
           

2.2 同步請求

以同步模式發出的請求會暫停所有js代碼的執行,直到從伺服器獲得響應為止。其應用代碼比較簡潔:

var request =new XMLHttpRequest();
request.open("GET","",false);
request.send(null);

var status =request.status;
//XMLHttpRequest的status屬性,包含與伺服器響應一起發送的http狀态碼

if(status ==200){
    alert("The text file was found");
}else {
    alert("code:"+status);
}
           

2.3 異步請求

大多數情況下都使用異步請求,它允許 XMLHttpRequest 對象等待伺服器的響應的同時,浏覽器繼續執行js代碼。

在異步請求中, XMLHttpRequest 對象提供了 readyState 屬性,該屬性包含一個數值,每個數值都表示請求生存期中的特定狀态:

數值 注釋
已建立對象,但未調用open()方法
1 已調用open()方法,但未發送請求
2 已發送請求,标題和狀态已接收并可用
3 接收到來自伺服器的響應
4 接收完請求資料

當 readyState 發生變化的時候,都會觸發onreadystatechange事件

var request =new XMLHttpRequest();

function reqReadyStateChange() {
    if(request.readyState == 4){    //浏覽器知道伺服器已經收到自己的請求
        
        var status =request.status;
        if(status == 200){
            alert(request.responseText);  //傳回文本的資料
        }else {1720
            alert("code:"+status);
        }
    }
    
request.open("GET",url);
request.onreadystatechange = reqReadyStateChange;
request.send(null);
}

           

3 自定義HttpRequest子產品

建立HttpRequest子產品

//定義一個 HttpRequest 引用類型(類)
function HttpRequest(url, callback) {
    this.request = new XMLHttpRequest();
    this.request.open("GET", url);

    var tempRequest = this.request;  
    //this指向的是XMLHttpRequest對象,而不是reqReadyStateChange函數
    
    function reqReadyStateChange() {
        //在函數中又定義了一個函數
        if (tempRequest.readyState == 4) {
            if (tempRequest.status == 200) {
                callback(tempRequest.responseText);
            } else {
                alert("An error occurred trying to contact the server.");
            }
        }
    }
    
    this.request.onreadystatechange = reqReadyStateChange;
}

HttpRequest.prototype.send = function () {   //重構一個不需要參數的send()方法
    this.request.send(null);
};

           

使用以上自定義的子產品

//建立一個函數用于顯示接收到的資料
function handleData(text){
    alert(text);
}

var request = new HttpRequest("http://localhost:63342/123.txt",handleData);
request.send();