Ajax异步&同步请求

时间:2021-05-10 13:30:07

一、简介

Ajax请求最重要的问题是代码执行的顺序。最长遇到的问题是,我们定义一个变量接收ajax异步请求的返回结果,后续代码使用,然而后续代码在使用时该变量为初始值,始终得不到想要的结果!!!

二、示例

// 异步
var  email = "test@ptmind.com";
console.log(1);
jQuery.ajax({
	url: "/invite/sendEmailAjax.pt",
	type: "post",
	dataType: "text",
	async: true,
	data: "inviteEmails="+email,
	success: function(data){
		console.log(2);
	}
});
console.log(3);
// 结果:1->3->2

// 同步
var  email = "test@ptmind.com";
console.log(1);
jQuery.ajax({
	url: "/invite/sendEmailAjax.pt",
	type: "post",
	dataType: "text",
	async: false,
	data: "inviteEmails="+email,
	success: function(data){
		console.log(2);
	}
});
console.log(3);
// 结果:1->2->3

三、官方解释

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

sync默认是true,即为异步方式,$.ajax执行后,会继续执行ajax后面的脚本,直到服务器端返回数据后,触发$.ajax里的success方法。若要将其设置为false,则所有的请求均为同步请求,在没有返回值之前,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
http://api.jquery.com/jQuery.ajax/