ajax同步模式和異步模式的區別就是在於,xhr.open()方法第3個參數傳入的bool值的區別,xhr.open()方法第3個參數的作用就是設置此次請求是否採用異步模式執行,默認為true ,那麼同步模式xhr.open()方法第3個參數值就是false了。
1.ajax異步模式:hr.open()方法第3個參數值為true(默認值)
console.log('before ajax')
var xhr = new XMLHttpRequest()
// 默認第三個參數為 true 意味著採用異步方式執行
xhr.open('GET', './test.php', true)
xhr.send(null)
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
// 這裡的代碼最後執行
console.log('request done') 10}
}
console.log('after ajax')
2.ajax同步模式:hr.open()方法第3個參數值為false,以下這個例子採用同步方式執行,則代碼會卡死在這一步:
console.log('before ajax')
var xhr = new XMLHttpRequest()
// 同步方式
xhr.open('GET', './test.php', false)
// 同步方式 執行需要 先註冊事件再調用 send,否則 readystatechange 無法觸發
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
// 這裡的代碼最後執行
console.log('request done') 10}
}
xhr.send(null)
console.log('after ajax')
特別注意:同步模式和異步模式的差異,就是一定在發送請求之前註冊事件,不管同步或者異步,為了讓這個事件可以更加可靠一定要觸發,一定是先註冊了事件,切記不要使用同步模式。
原文地址:http://tangjiusheng.com/ajax/149.html
閱讀更多 湯久生前端 的文章