ajax异步实验

在前端中,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里面执行,就可以保证是按照代码顺序执行的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值