Javascript - AJAX

AJAX 特性是無須重載整個頁面,便能對遠端server 發送請求。

AJAX

利用 JavaScript 的 XMLHttpRequest 物件與遠端server 進行非同步的資料交換。
特性是無須重載整個頁面,便能對遠端server 發送請求。

流程

new XMLHttpRequest()
建立 HTTP 請求。

.open(method, url[, async])
open 方法指定請求。

  • method : 指定 HTTP method (GET, POST, PUT, DELETE…)。
  • url : 目標網址。
  • async : true(非同步,預設) / false (同步) 。

.send(null | formData)
如果method是用POST,第一個參數是 Form data 格式。

.setRequestHeader(header, value)
如果method是用POST,需要設定 HTTP header,要在open()後、send()前呼叫。

  • header : Content-Type
  • value-HTML表單類型資料 : application/x-www-form-urlencoded
  • value-JSON格式資料 : application/json
  • value-XML格式資料 : text/xml

事件

.onreadystatechange
當 XMLHttpRequest 物件狀態改變時,透過 onreadystatechange 綁定的函數就會被執行。

屬性

.readyState
當前 XMLHttpRequest 物件狀態。值:

  • 0 : 未連結(沒open)
  • 1 : 未傳送(有open,沒send)
  • 2 : 請求(有send)
  • 3 : 回應資料中
  • 4 : 回應完成

.statusText
返回的回應狀態。值:

  • 1xx : 參考的資訊。
  • 2xx : 成功。 例如: 200 – ok
  • 3xx : 重新導向。
  • 4xx : 錯誤。 例如: 404 – not found
  • 5xx : server錯誤。

.responseText
請求返回的資料字串。

GET請求範例

1
2
3
4
5
6
7
8
9
10
11
12
13
 var xhr = new XMLHttpRequest();

xhr.open('get', url);

xhr.send(null);

xhr.onreadystatechange = function () {
if (httpRequest.readyState === 4) {
if (httpRequest.status == 200) {
console.log(xhr.responseText)
}
}
}

POST請求範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 var xhr = new XMLHttpRequest();

xhr.open('post', url);

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

xhr.send('email = abcde123@gmail.com & password = 1234');

xhr.onreadystatechange = function () {
if (httpRequest.readyState === 4) {
if (httpRequest.status == 200) {
console.log(xhr.responseText)
}
}
}
作者

LeeU

發表於

2020-12-01

更新於

2024-04-04

許可協議