AJAX
原生AJAX
- AJAX簡介:
- AJAX 全稱 Asynchronous Javascript And XML,就是異步的 JS 和 XML
- 通過 AJAX 可以再瀏覽器中向服務器發送異步請求,最大優勢:頁面無刷新獲取數據
- AJAX 不是新的編程語言,而是一種將現有的標準集合在一期使用的新方式
- XML簡介:
- XML 可擴展標記語言
- XML 被設計用來傳輸和存儲數據
- XML 和 HTML 類似,不同的是 HTML 仲都是預定義標籤,而 XML 仲沒有預定義標籤,都是自定義標籤,用來表示一些數據
1
2
3
4
5<student>
<name>Donald</name>
<age>18</age>
<gender>Male</gender>
</student> - 現在已經被 JSON 取代了
1
{"name":"Donald", "age":18, "gender":"Male"}
- AJAX特點:
- 優點:
- 可以無需刷新頁面而與服務器進行通信
- 允許你根據用戶事件來更部分分頁內容
- 缺點:
- 沒有瀏覽史,不能回退
- 存在跨域問題(可解決)
- SEO 不友好
- 優點:
AJAX基本使用
- 核心對象
XMLHttpRequest- AJAX的所有操作都是用過該對象進行
使用步驟:
創建
XMLHttpRequest實例對象1
const xhr = new XMLHttpRequest()
指定發送請求的:方法(
methods)和地址(url)1
xhr.open('GET', 'http://127.0.0.1:8080/test_get')
發送請求
1
xhr.send()
接收數據
1
2
3
4
5
6
7
8// 綁定監聽狀態
xhr.onreadystatechange = () => {
// 當監聽狀態等於 4 表示數據接收完畢
if(xhr.readyState === 4){
// xhr.response 獲取數據
content.innerHTML = `<h3>${xhr.response}</h3>`
}
}
xhr內部的五種狀態
- 5種狀態的值分別為:
0、1、2、3、40:實例出來的那一刻(初始狀態)1:open已經調用了,但是send還沒有調用,此時可以修改請求頭內容2:send已經調用了,已經無法修改請求頭3:已經回來一部分數據,小的數據會在此階段一次性接收完畢,較大的數據有待進一步接收,響應頭一定回來4:數據全部接收完畢
GET請求
攜帶
query參數指定請求:
- 使用
query參數 (urlencoded) 編碼形式:key=value&key=value1
xhr.open('GET', 'http://127.0.0.1:8080/test_get?name=Donald&age=18')
- 使用
接收參數:
- 使用
request.query屬性1
2
3app.get('/test_get/', (request, response) => {
console.log(request.query)
})
- 使用
攜帶
params參數指定請求:
- 使用
params參數形式:xxx/xxx/Donald/181
xhr.open('GET', 'http://127.0.0.1:8080/test_get/Donald/18')
- 使用
接收參數:
- 使用
request.params屬性 - 地址配置佔位符 (
/:name/:age)1
2
3
4// 佔位符
app.get('/test_get/:name/:age', (request, response) => {
console.log(request.params)
})
- 使用
POST請求
攜帶
query參數指定請求:
- 使用
query參數 (urlencoded) 編碼形式1
xhr.open('POST', 'http://127.0.0.1:8080/test_post?name=Donald&age=18')
- 使用
接收參數:
- 使用
request.query屬性1
2
3app.post('/test_post/', (request, response) => {
console.log(request.query)
})
- 使用
攜帶
params參數指定請求:
- 使用
params參數形式1
xhr.open('POST', 'http://127.0.0.1:8080/test_post/Donald/18')
- 使用
接收參數:
- 使用
request.params屬性 - 地址配置佔位符 (
/:name/:age)1
2
3
4// 佔位符
app.post('/test_post/:name/:age', (request, response) => {
console.log(request.params)
})
- 使用
使用請求體的
urlencode編碼形式指定請求:
- 不需要在地址中添加
1
xhr.open('POST', 'http://127.0.0.1:8080/test_post')
- 不需要在地址中添加
追加響應頭:
- 用於表示攜帶請求體參數的
urlencode編碼形式1
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
- 用於表示攜帶請求體參數的
發送請求:
- 在發送請求時傳入參數
1
xhr.send('name=Donald&age=18')
- 在發送請求時傳入參數
使用中間件解析:
- 引入中間件解析
urlencoded編碼形式的請求體參數1
app.use(express.urlencoded({extended:true}))
- 引入中間件解析
接收參數:
- 使用
request.body屬性1
2
3app.post('/test_post', (request, response) => {
console.log(request.body)
})
- 使用
使用請求體的
json編碼形式指定請求:
- 不需要在地址中添加
1
xhr.open('POST', 'http://127.0.0.1:8080/test_post')
- 不需要在地址中添加
追加響應頭:
- 用於表示攜帶請求體參數的
json編碼形式1
xhr.setRequestHeader('Content-type', 'application/json')
- 用於表示攜帶請求體參數的
發送請求:
- 在發送請求時傳入參數
JSON.stringify對象,讓其轉換為JSON字符串1
2const person = {name:'Donald', age:18}
xhr.send(JSON.stringify(person))
使用中間件解析:
- 引入中間件解析
json編碼形式的請求體參數1
app.use(express.json())
- 引入中間件解析
接收參數:
- 使用
request.body屬性1
2
3app.post('/test_post', (request, response) => {
console.log(request.body)
})
- 使用
解析JSON數據
- 解析JSON格式數據:
- 在獲取數據之後使用
JSON.parse函數解析1
2const result = JSON.parse(xhr.response)
console.log(result) - 問題:如果服務器返回的數據非 JSON 格式則會報錯
- 在獲取數據之後使用
xhr的API解析JSON格式:- 配置
xhr.responseType屬性為json1
xhr.responseType = 'json'
- 服務器返回數據後就會進行 JSON 格式的解析,如果返回數據非 JSON 格式則
response為null
- 配置
請求異常與超時處理
- 處理請求異常:
- 使用
xhr.onerror配置請求異常的回調函數1
2
3xhr.onerror = () => {
alert('Request Error')
}
- 使用
- 處理超時問題:
- 使用
xhr.timeout設置請求時限,如果超過時限則取消請求 - 使用
xhr.ontimeout配置超時的回調函數1
2
3
4
5
6
7// 超時時間
xhr.timeout = 2000
// 超時的回調
xhr.ontimeout = () => {
alert('Request Timeout');
}
- 使用
取消請求
- 取消請求:
- 使用
xhr.abort函數可以取消該次請求1
xhr.abort()
- 使用
- 工作原理:
- 測試編碼:
1
2xhr.send()
xhr.abort() - 如果發送請求之後立即取消請求,該次請求是有可能已經發送到服務器,但也獲取不到數據,因為瀏覽器會將服務器的響應攔截
- 簡而言之,然後速度夠快,在請求沒有發送到服務器之前被攔截並取消,如果請求發送到服務器,那麼瀏覽器也會攔截服務器的響應
- 測試編碼:
避免多次重複請求
- 配置一個
isLoading屬性判斷請求是否發送中,如果發送中,再次發生請求則關閉上次的請求1
2
3
4
5
6
7
8
9
10
11
12
13let xhr
let isLoading
btn.onclick = () => {
if(isLoading) xhr.abort() // 如果發送請求中則取消該次請求
xhr.onreadystatechange = () => {
if(xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)){
isLoading = false // 接收到數據後為 false
}
}
xhr.send()
isLoading = true // 發生請求後為 true
}
jQuery
GET請求
- 完整版:
1
2
3
4
5
6
7
8
9
10
11
12
13$.ajax({
url: 'http://127.0.0.1:8080/test_jquery_get', // 請求地址
method: 'GET', // 請求方式(默認值GET)
dataType: 'json', // 配置響應數據格式
data: {}, // 攜帶的數據
timeout: 2000, // 指定超時時間
success: (result, responseText, xhr) => { // 成功的回調
result // 服務器的響應數據
responseText // 響應結果 (success)
xhr // xhr 構造函數
},
error: () => {}, // 失敗的回調
})
- 精簡版:
1
2
3$.get('http://127.0.0.1:8080/test_jquery_get', {}, (data) => {
console.log(data)
},'json')
- 備註:攜帶的數據默認是
query格式,可以使用params格式,不過要在url和服務器追加上追加
POST請求
- 完整版:
1
2
3
4
5
6
7
8
9
10
11
12
13$.ajax({
url: 'http://127.0.0.1:8080/test_jquery_post', // 請求地址
method: 'POST', // 請求方式(默認值GET)
dataType: 'json', // 配置響應數據格式
data: {}, // 攜帶的數據
timeout: 2000, // 指定超時時間
success: (result, responseText, xhr) => { // 成功的回調
result // 服務器的響應數據
responseText // 響應結果 (success)
xhr // xhr 構造函數
},
error: () => {}, // 失敗的回調
})
- 精簡版:
1
2
3$.post('http://127.0.0.1:8080/test_jquery_post', {}, (data) => {
console.log(data)
},'json')
- 備註:攜帶的數據默認是
query格式,可以使用params格式,不過要在url和服務器追加上追加
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.


