在前端中,ajax经常被使用。以下我们看看ajax的异步是怎样表现出来的:
<!DOCTYPE html>
<html>
<body>
<script src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
$.get('index.php', {}, function(response){
console.log('1st');
});
$.get('login.php', {}, function(response){
console.log('2nd');
});
$.get('2.php', {}, function(response){
console.log('3rd');
});
$.get('post.php', {}, function(response){
console.log('4th');
});
</script>
</body>
</html>
打开F12-Console,看到顺序是1-3-2-4,证明ajax的异步性,不知按代码顺序执行的。
<!DOCTYPE html>
<html>
<body>
<script src="//cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
$.ajax({
url: 'index.php',
data: {},
async: false,
success: function(response){
console.log('1st');
},
});
$.ajax({
url: 'login.php',
data: {},
async: false,
success: function(response){
console.log('2nd');
},
});
$.ajax({
url: 'login.php',
data: {},
async: false,
success: function(response){
console.log('3rd');
},
});
$.ajax({
url: '2.php',
data: {},
async: false,
success: function(response){
console.log('4th');
},
});
</script>
</body>
</html>
换成更底层的JQuery ajax函数,将async属性设为false,就可以让这几个ajax按顺序执行了。
这里的警告:Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
中文翻译:在主线程上同步XMLHttpRequest弃用,因为其不利影响最终用户的体验
就是说,异步已经被我们关闭了。
在前端开发中,我遇到过“全局变量无法被赋值”的情况,其实这是因为ajax异步的特性造成的,只要规定ajax不再异步,或者嵌套在success、complete里面执行,就可以保证是按照代码顺序执行的。