ajax同步模式和异步模式的区别就是在于,xhr.open()方法第3个参数传入的bool值的区别,xhr.open()方法第3个参数的作用就是设置此次请求是否采用异步模式执行,默认为true ,那么同步模式xhr.open()方法第3个参数值就是false了。
1.ajax异步模式:hr.open()方法第3个参数值为true(默认值)
1 2 3 4 5 6 7 8 9 10 11 | 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,以下这个例子采用同步方式执行,则代码会卡死在这一步:
1 2 3 4 5 6 7 8 9 10 11 12 | 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' ) |
特别注意:同步模式和异步模式的差异,就是一定在发送请求之前注册事件,不管同步或者异步,为了让这个事件可以更加可靠一定要触发,一定是先注册了事件,切记不要使用同步模式。
原文地址:https://blog.deisuan.com/ajax/149.html