/*常见错误示例 ?直接在 ajax 里面return 结果*/ function demo(){ ????$.ajax({ ????????url : ‘test.do‘, ????????type : "post", ????????data : {}, ????????async : false, ????????success : function(data) { ????????????return 2; ????????} ????}); }/* 结果 ?无返回 */
两个错误写法会导致这种情况:
1.ajax默认为异步,异步不可以直接return返回结果
2.在ajax方法中直接return返回值,嵌套函数中,return该作用域函数的返回值,demo中,demo()为外部函数,return的结果对demo()无效
正确姿势如下
41 /**42 ?* (1)同步调用 (2)且在ajax对全局变量进行设值 (3)ajax函数外将变量return43 ?* 结果:返回 2。成功获取返回值44 ?* 成功原因:先执行result = 2;再往下执行return result;45 ?*/46 function demo1(){47 ????var result = 1;48 ????$.ajax({49 ????????url : ‘test.do‘,50 ????????type : "post",51 ????????data : {},52 ????????async : false,53 ????????success : function(data) {54 ????????????result = 2;55 ????????}56 ????});57 ????return result; ?//258 }
$.ajax() 获取不到return 返回值
原文地址:http://www.cnblogs.com/AllenChou/p/7680650.html