原生js發送Ajax請求


一、通過onload注冊事件

// 1. 創建一個 xhr 對象
var xhr = new XMLHttpRequest();
// 2. 設置請求的方式和路徑
xhr.open('GET', '/time');
// 3. 發送請求
xhr.send(null);
// 4. 注冊事件
xhr.onload = function () {
    // 通過 xhr 的 responseText 獲取到響應的響應體
   console.log(this.responseText)
}

  注意:如果是發送post方式的請求,需要在open和send中間設置請求頭,send中添加要傳遞的參數(有格式要求:=連接屬性和值;&連接不同的屬性)。

var xhr = new XMLHttpRequest()
xhr.open('POST', '/query-post')
// 設置 Content-Type 為 application/x-www-form-urlencoded,這行代碼不用死記硬背,去復制即可
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// 需要提交到服務端的數據可以通過 send 方法的參數傳遞
// 格式:name=zhangsan&age=18
xhr.send('name=zhangsan&age=18')
xhr.onload = function () {
    console.log(this.responseText)
}

二、通過onreadystatechange注冊事件

  onload 是 HTML5 以后新增的方便獲取響應的事件,過去獲取瀏覽器返回內容的時候使用的是 onreadystatechange。

var xhr = new XMLHttpRequest()
// open 方法的第一個參數的作用就是設置請求的 method
xhr.open('POST', '/query-post')
// 設置 Content-Type 為 application/x-www-form-urlencoded,這行代碼不用死記硬背,去復制即可
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// 需要提交到服務端的數據可以通過 send 方法的參數傳遞
// 格式:name=zhangsan&age=18
xhr.send('name=zhangsan&age=18')
// 更改事件為onreadystatechange
xhr.onreadystatechange = function () {
    if (this.readyState === 4) {
    // 后續邏輯......
  }
} 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM