1. 程式人生 > 其它 >用原生js的方式發起網路請求

用原生js的方式發起網路請求

用原生js發起網路請求:

首先要明確的是,什麼是XMLHttpRequest?

(XMLHttpRequest)簡稱xhr,是瀏覽器提供的javascript物件,我們可以通過與這個物件,請求伺服器上面的資料資源,不管是jQuery的Ajax函式還是別的框架,都是基於xhr,進行封裝出來的;

使用xhr發起GET請求

步驟:

1.建立xhr物件;

2.呼叫xhr.open()函式;

3.呼叫xhr.send()函式;

4.監聽xhr.onreadystatechange事件;

 1 // 建立XHR物件
 2         var xhr = new XMLHttpRequest();
 3
// 呼叫open函式 4 xhr.open("GET", 5 "http://www.liulongbin.top:3006/api/getbooks") 6 // 呼叫send函式,發起請求 7 xhr.send() 8 // 監聽onreadystatechange事件 9 xhr.onreadystatechange = function () { 10 //判斷伺服器返回的狀態資訊是否全等於4且http響應狀態碼是否等於200; 11 if (xhr.readyState === 4 && xhr.status === 200) {
12 //列印JSON字串形式的伺服器響應資料; 13 console.log(xhr.responseText); 14 //檢測資料型別返回string 15 console.log(typeof xhr.responseText); 16 } 17 }

xhr.readyState:狀態資訊。而且狀態也是不可逆的;

0:請求未初始化,還沒有呼叫 open()。

1:請求已經建立,但是還沒有傳送,還沒有呼叫 send()。

2:請求已傳送,正在處理中(通常現在可以從響應中獲取內容頭)。

3:請求在處理中;通常響應中已有部分資料可用了,沒有全部完成。

4:響應已完成;您可以獲取並使用伺服器的響應了。

xhr.status:HTTP響應狀態碼;

[資訊響應]( `100`– `199`);
[成功響應]( `200`– `299`);
[重定向訊息]( `300`– `399`);
[客戶端錯誤響應]( `400`– `499`);
[伺服器錯誤響應]( `500`- `599`);

使用xhr發起帶引數的get請求;

只需要在呼叫xhr.open期間,為url地址指定引數就可以了;

xhr.open("GET", "http://www.liulongbin.top:3006/api/getbooks?id=1")

這種在URL地址後面拼接的引數,叫做查詢字串;

GET請求攜帶引數的本質:

無論使用$.ajax(),還是使用$.get(),又或者直接使用xhr物件發起的get請求,當需要攜帶引數的時候,本質上,都是直接將引數以查詢字串的形式,追加到URL的後面,傳送到伺服器的;

$.get('url',{name:'ss',age:20},function(){})
//等價於
$.get('url?name=ss&age=20',function(){})

$.ajax({method:'GET',url:'url',data:{name:'ss',age:20},success:function(){}})
//等價於        
$.ajax({method:'GET',url:'url?name=ss&age=20',success:function(){}})

使用xhr發起post請求;

步驟:

建立xhr物件

呼叫xhr.open()函式

設定Content-Type屬性(固定的寫法)

呼叫xhr.send()函式,指定傳送的資料;

監聽xhr.onreadystatechange1 // 1. 建立 xhr 物件

 2         var xhr = new XMLHttpRequest();
 3         // 2. 呼叫 open 函式
 4         xhr.open("POST", "http://www.liulongbin.top:3006/api/addbook");
 5         // 3. 設定 Content-Type 屬性(固定寫法)
 6         xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 7         // 4. 呼叫 send 函式
 8         xhr.send(`bookname=yyds&author=yyds&publisher=yyds`);
 9         // 5. 監聽事件
10         xhr.onreadystatechange = function () {
11             if (xhr.readyState === 4 && xhr.status === 200) {
12                 console.log(xhr.responseText);
13                 console.log(typeof xhr.responseText);
14                    //JSON.parse方法可以把伺服器返回過來的JSON字串資料轉化為物件的形式;
15                     var result = JSON.parse(xhr.responseText)
16                     //控制檯列印轉化的完成的物件;
17                     console.log(result)
18                     //列印物件,以陣列的形式返回
19                     console.log(result.data)
20                   //相反JSON.stringify()方法,可以把物件轉化為JSON字串資料的形式
21                     var json=JSON.stringify(result)
              console.log(json)
22 } 23 }

資料物件 轉換為 字串的過程,叫做序列化,例如:呼叫 JSON.stringify() 函式的操作,叫做 JSON 序列化。

字串 轉換為 資料物件的過程,叫做反序列化,例如:呼叫 JSON.parse() 函式的操作,叫做 JSON 反序列化。