XHR理解
使用XMLHttpRequest (XHR)物件可以與服務器互動, 也就是發送ajax請求,前端可以獲取到資料,而無需讓整個的頁面重繪,這使得Web頁面可以只更新頁面的區域,而不影響用戶的操作,
-
xhr物件本身有5種狀態:xhr “誕生” 的那一刻就是0狀態:
0:xhr物件在實體化出來的那一刻,就已經是0狀態,代表著xhr是初始化狀態,
1:send方法還沒有被呼叫,即:請求沒有發出去,此時依然可以修改請求頭,
2:send方法被呼叫了,即:請求已經發出去了,此時已經不可以再修改請求頭,
3:已經回來一部分資料了,如果是比較小的資料,會在此階段一次性接收完畢,較大資料,有待于進一步接收,
4:資料完美的回來了,
原生的ajax請求
- get請求
1.實體化一個XMLHttpRequest物件
let xhr = new XMLHttpRequest()
2.系結一個名為onreadystatechange事件監聽
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200){
//如果進入此判斷,意味著:請求成功了,且資料已經回來了
console.log(xhr.response)
}
}
3.呼叫open方法---------用什么方法發?給誰發?帶著什么過去?
xhr.open('get','http://localhost:3000/ajax_get?name=kobe&age=18&t='+Date.now())
4.呼叫send方法---------發送請求
xhr.send()
- post請求
1.實體化一個XMLHttpRequest物件
let xhr = new XMLHttpRequest()
2.系結一個名為onreadystatechange事件監聽
xhr.onreadystatechange = function () {
if(xhr.readyState === 4 && xhr.status === 200){
console.log(xhr.response)
let demo = document.getElementById('demo')
demo.innerHTML = xhr.response
}
}
3.呼叫open方法---------用什么方法發?給誰發?帶著什么過去?
xhr.open('post','http://localhost:3000/ajax_post')
特別注意:此處是設定post請求所特有的請求頭,若不設定,服務器無法獲取引數
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
4.呼叫send方法---------發送請求
xhr.send('name=kobe&age=18')
JQuery封裝的ajax請求
- get請求
1、完整的寫法
$.ajax({
url:'http://localhost:3000/ajax_get',
method:'get', //發送請求的方式
data:{name:'kobe',age:41}, //發送請求攜帶的資料
//成功的回呼
success:function (result) {
console.log(result)
},
//失敗的回呼
error:function (err) {
console.log(err)
}
})
2、簡單的寫法
$.get('http://localhost:3000/ajax_get',{name:'kobe',age:41},(data)=>{
console.log(data)
})
- post請求
1、完整的寫法
$.ajax({
url:'http://localhost:3000/ajax_post',
method:'post', //發送請求的方式
data:{name:'kobe',age:41}, //發送請求攜帶的資料
//成功的回呼
success:function (result) {
console.log(result)
},
//失敗的回呼
error:function (err) {
console.log(err)
}
})
2、簡單的寫法
$.post('http://localhost:3000/ajax_post',{name:'kobe',age:41},(data)=>{
console.log(data)
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/223571.html
標籤:其他
上一篇:兩邊寬度固定,中間自適應的布局實作總結(重點學習網格布局)
下一篇:Vue 3 應用API講解
