jquery中,ajax返回值,获取不到。
两种原因会导致这种情况:1.ajax未用同步 2.在ajax方法中直接return返回值。
下面列举了三种写法,只有第三种可正确获取到返回值:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
/** *
async:false,同步调用 *
返回1:2 *
失败 *
分析:ajax内部是一个或多个定义的函数,ajax中return返回值,返回到ajax定义函数,而不是ajax外层的函数 */ function checkAccount1(){ var result
= "1:2" ; $.ajax({ url
: path+ '/user/checkAccount.do' , type
: "post" , data
: {}, 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
: {}, 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
: {}, async
: false , success
: function (data)
{ result
= "3:1" ; } }); return result; }
|