JQuery Ajax返回值正常但函数调用结果为undefined问题求解
问题原因
- 核心是AJAX默认是异步执行的:你调用
checkWeekendHollidays函数时,AJAX请求还在后台发送,函数不会等请求返回就直接执行结束,自然没有返回值,所以console.log打印undefined。 - 你写的return语句作用域错误:
return ( _first_weekday == 0 || _last_weekday_id >= 6 || _result!="0" )这行是在done的匿名回调函数里,返回值只会被jQuery的回调体系接收,不会作为外层checkWeekendHollidays函数的返回值向外传递。 - 额外小问题:fail回调里打印的
_resultado变量拼写错误,你定义的参数是_result,运行时会报变量未定义错误。
解决方案
方案1:用回调函数处理结果
把需要用到返回值的逻辑封装成回调函数,传入checkWeekendHollidays,等AJAX请求完成后调用回调传递结果:
// 函数改造 function checkWeekendHollidays(_i, callback) { // 你的其他逻辑,比如获取_date1、_date2、_first_weekday、_last_weekday_id的代码 $.ajax({ url: "./directory/ajax_check_weekend_hollidays.php", type: "POST", data: { start_date: _date1, final_date: _date2 } }).done(function (_result) { const res = ( _first_weekday == 0 || _last_weekday_id >= 6 || _result!="0" ); callback(null, res); }).fail(function (_result) { console.log("ERROR:" + _result); callback(_result, null); }); } // 调用方式 checkWeekendHollidays(_i, function(err, _has_weekend_hollidays) { if (err) return; console.log(_has_weekend_hollidays); // 后续所有用到_has_weekend_hollidays的逻辑都写在这里 });
方案2:用Promise+async/await写法(更简洁)
$.ajax本身返回jQuery的Deferred对象,兼容Promise规范,可以直接用async/await简化异步逻辑:
// 函数改造,直接返回ajax对象 function checkWeekendHollidays(_i) { // 你的其他逻辑,比如获取_date1、_date2、_first_weekday、_last_weekday_id的代码 return $.ajax({ url: "./directory/ajax_check_weekend_hollidays.php", type: "POST", data: { start_date: _date1, final_date: _date2 } }).then(function (_result) { return ( _first_weekday == 0 || _last_weekday_id >= 6 || _result!="0" ); }).fail(function (_result) { console.log("ERROR:" + _result); }); } // 调用方式,在async函数里用await接收结果 async function yourMainLogic() { const _has_weekend_hollidays = await checkWeekendHollidays(_i); console.log(_has_weekend_hollidays); // 后续用到_has_weekend_hollidays的逻辑 } yourMainLogic();
内容的提问来源于stack exchange,提问作者Ana Souza
相关产品推荐
相关产品推荐

