1. 程式人生 > >原生ajax請求的使用

原生ajax請求的使用

注:請求地址是自己的專案地址,請自行更改。

這只是一個簡單的原生XMLHttpRequst的使用,之後會發如何封裝原生ajax實現jequery的ajax

第一步:建立xhr物件。

const xhr = new XMLHttpRequest();

第二步:open()設定。

xhr.open('PUT','http://118.24.84.199:8080/sm/accept/list',false);

第三步:設定介面需要的頭部。

xhr.setRequestHeader('token','515b8c62-ddf4-41ef-a7c8-93957e1c589e');
xhr.setRequestHeader('Accept','application/json');
xhr.setRequestHeader('Content-Type','application/json');

第四步:傳送請求資料。

注意:這裡的資料需要進行處理,處理為json檔案,使用JSON.stringify處理。
let data = {
                page:1,
                pageSize:10,
            };
data = JSON.stringify(data);
xhr.send(data);

到這裡就已經發送了,可以在瀏覽器的網路請求中檢視請求的情況。

clipboard.png

但是在頁面中還沒有進行資料處理

如果資料是同步請求:直接在send()語句之後對資料進行處理。
console.log(xhr.response);
但是一般情況下資料的請求都是非同步的,那麼就要使用onreadystatechange這個事件對資料進行處理。
接收到資料之後將其列印。
xhr.onreadystatechange = function(event){
    if (xhr.readyState == 4){
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
            console.log(JSON.parse(xhr.response));
        } else {
            console.log("Request was unsuccessful: " + xhr.status);
        }
    }
};