首页 > 技术文章 > ajax 返回值问题

daixiaotian 2017-02-15 17:22 原文

错误示例:
function returnFlag(){ $.ajax({ type:"post", dataType:"json", data:JSON.stringify({"verifyCode":yzm}), url:config.proofCodeUrl, xhrFields: { withCredentials: true }, async:false, success:function(result){ if(result.code==200){ res = result.data; if(res.flag == 1){//比对成功,再给发送验证码的功能 return true; }else{//比对失败 swal("输入图片验证码错误") $(".yzm > img").trigger("click");//更换图片验证码 $('#randomcode').val(''); $('#randomcode')[0].focus(); } }else{ swal(result.info); } } }); return false; }

  实测发现函数返回的值始终是undefined,没有得到期望的值。

原因:返回的是回掉函数,而不是returnFlag的

正确示例:
function returnFlag(){ var flag = false; $.ajax({ type:"post", dataType:"json", data:JSON.stringify({"verifyCode":yzm}), url:config.proofCodeUrl, xhrFields: { withCredentials: true }, async:false, success:function(result){ if(result.code==200){ res = result.data; if(res.flag == 1){//比对成功,再给发送验证码的功能 flag = true; }else{//比对失败 swal("输入图片验证码错误") $(".yzm > img").trigger("click");//更换图片验证码 $('#randomcode').val(''); $('#randomcode')[0].focus(); } }else{ swal(result.info); } } }); return flag; }

  

推荐阅读