促进回调的onSuccess返回值的调用函数返回值 [英] Promote callback onSuccess return value to the Caller Function return value
问题描述
我有一个JavaScript函数来调用一个通用的功能进行AJAX调用服务器。我需要从Ajax调用回调函数检索结果(真/假),但结果我得到的总是未定义。
I have a javascript function that calls a generic function to make an ajax call to the server. I need to retrieve a result (true/false) from the callback function of the ajax call, but the result I get is always 'undefined'.
通用功能的超简化的版本,而我所有的逻辑是:
A super-simplified version of the generic function without all my logic would be:
function CallServer(urlController) {
$.ajax({
type: "POST",
url: urlController,
async: false,
data: $("form").serialize(),
success:
function(result) {
if (someLogic)
return true;
else
return false;
},
error:
function(errorThrown) {
return false;
}
});
}
和函数调用它会是这样的:
And the function calling it would be something like:
function Next() {
var result = CallServer("/Signum/TrySave");
if (result == true) {
document.forms[0].submit();
}
}
结果变量始终是未定义,并调试它,我可以看到,回归真正的行回调函数正在执行。
The "result" variable is always 'undefined', and debugging it I can see that the "return true" line of the callback function is being executed.
为什么发生这种情况的任何想法?我怎么能的泡沫的从回调函数的返回值的CallServer功能?
Any ideas of why this is happening? How could I bubble the return value from the callback function to the CallServer function?
感谢
推荐答案
刚刚找到如何做到这一点:)声明一个变量,然后从回调函数相应地更新它。后来我可以返回变量。我把code为未来的读者:
Just found how to do it :) Declaring a variable and updating it accordingly from the callback function. Afterwards I can return that variable. I place the code for future readers:
function CallServer(urlController) {
var returnValue = false;
$.ajax({
type: "POST",
url: urlController,
async: false,
data: $("form").serialize(),
success:
function(result) {
if (someLogic){
returnValue = true;
return;
}
},
error:
function(errorThrown) {
alert("Error occured: " + errorThrown);
}
});
return returnValue;
}
这篇关于促进回调的onSuccess返回值的调用函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!