ajax返回true / false – 我实现了一个回调
首先我已经阅读过这个主题jQuery AJAX函数返回true或false只返回false而它的一切都很好 , 在回调函数中返回jQuery的ajax数据参数是什么? , 如何返回数据响应ajax的真或假function? 我无法弄清楚如何使这个工作。
$("#btn_go").on('click', function(){ if(validateUserDetails() == false){ return; } });
因此,函数validateUserDetails
具有以下内容:
function validateUserDetails(){ var bool = false; $.ajax({ url: 'response.php?type=validateUserDetails', type: 'POST', dataType: 'json', data: {name: $("#checkout_name").val(), email: $("#checkout_email").val(), "country": $("#checkout_country").val(), "city": $("#checkout_city").val()}, success: function(data){ console.log(data); // this is currently returning FALSE // Which is totally correct! if(data == true){ bool = true; } return trueOrFalse(bool); } }); } function trueOrFalse(bool){ return bool; }
但这不起作用,因为如果我输出函数我得到“未定义”,这意味着该函数没有重新调整正确的值。 console.log(validateUserDetails()); // = undefined
我在做什么?
ajax
请求是asyncronous
。 不要使用sync: true
选项,这不是一个好主意。 你可以做的是使用ajax
返回的promise
,所以:
function validateUserDetails(){ return $.ajax({ url: 'response.php?type=validateUserDetails', type: 'POST', async: false, dataType: 'json', data: {name: $("#checkout_name").val(), email: $("#checkout_email").val(), "country": $("#checkout_country").val(), "city": $("#checkout_city").val()}, success: function(data){ console.log(data); // this is currently returning FALSE } });
}
$("#btn_go").on('click', function(){ validateUserDetails().done(function(data){ if(data == "someValue") return "whatever you want"; } });
由于还没有人回答,我会:
首先,您可以尝试同步请求
function validateUserDetails() { var bool = false; $.ajax({ url: 'response.php?type=validateUserDetails', type: 'POST', async: false, dataType: 'json', data: {name: $("#checkout_name").val(), email: $("#checkout_email").val(), "country": $("#checkout_country").val(), "city": $("#checkout_city").val()}, success: function(data) { console.log(data); // this is currently returning FALSE // Which is totally correct! if (data == true) { bool = true; } } }); return trueOrFalse(bool); }
如果不可接受,可以使用$ .Deferred()
function validateUserDetails() { var deferred = $.Deferred(); var bool = false; $.ajax({ url: 'response.php?type=validateUserDetails', type: 'POST', dataType: 'json', data: {name: $("#checkout_name").val(), email: $("#checkout_email").val(), "country": $("#checkout_country").val(), "city": $("#checkout_city").val()}, success: function(data) { console.log(data); // this is currently returning FALSE // Which is totally correct! if (data == true) { bool = true; } } complete: function () { deferred.resolve(trueOrFalse(bool)); } }); return deferred.promise(); } function test() { var promise = validateUserDetails(); promise.done(function(result) { console.log("Bool: " + result); }); }
你的函数validateUserDetails没有返回任何值,她只是执行一个异步函数。 异步函数返回true或false,但没有用于捕获它。
就像这样 :
function validateUserDetails(){ // asynchronous function $.ajax({...}); return undefined; }
如果你尝试console.log(trueOrFalse(bool));
你会看到“true”或“false”,但你不能将“return”用于异步函数。 你必须做一些成功的function,谁使用“数据”(日志,或其他function)