jquery中,ajax返回值,有三种写法,只有其中一种是成功的
/**
* async:false,同步调用
* 返回1:2
* 失败
* 分析:ajax内部是一个或多个定义的函数,ajax中return返回值,返回到ajax定义函数,而不是ajax外层的函数
*/
function checkAccount1(){
var result = "1:2";
$.ajax({
url : path+‘/user/checkAccount.do‘,
type : "post",
data : {‘account‘:"1",‘accType‘:1},
async : false,
success : function(data) {
return "1:1";
}
});
return result;
}
/**
* async:true,异步调用
* 返回1:2
* 失败
* 分析:result = "2:1"和后面return result异步执行,导致return result先执行
*/
function checkAccount2(){
var result = "2:2";
$.ajax({
url : path+‘/user/checkAccount.do‘,
type : "post",
data : {‘account‘:"1",‘accType‘:1},
async : true,
success : function(data) {
result = "2:1";
}
});
return result;
}
/**
* 同步调用,且在ajax对全局变量进行设值
* 返回:"3:1"
* 成功
* 分析:先执行result = "3:1";再往下执行return result;
*/
function checkAccount3(){
var result = "3:2";
$.ajax({
url : path+‘/user/checkAccount.do‘,
type : "post",
data : {‘account‘:"1",‘accType‘:1},
async : false,
success : function(data) {
result = "3:1";
}
});
return result;
}
原文:http://www.cnblogs.com/terryMe/p/6130309.html