ajax同步模式和异步模式的区别

释放双眼,带上耳机,听听看~!
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')

内容投诉
前端开发

WEB前端jQuery漂浮广告代码

2018-11-5 14:29:26

前端开发

巧用canvas实现网页截图

2018-11-6 9:47:14

搜索