Javascript jquery - 从回调函数(在发布请求中)返回值到其内部的函数中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7032858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery - return value from callback function (in post request) into the function its inside of?
提问by Ricardo Altamirano
I have a javascript function that posts data to a validation script and grabs a value from there. The callback function on the post request returns a boolean value, and I'm trying to get the entirefunction to return that boolean value. Right now, the callback function returns the correct value, but the function itself doesn't return anything. Here's the code:
我有一个 javascript 函数,可以将数据发布到验证脚本并从那里获取一个值。post 请求上的回调函数返回一个布尔值,我试图让整个函数返回该布尔值。现在,回调函数返回正确的值,但函数本身不返回任何内容。这是代码:
function validate(request_type, request_text) {
$.post("http://www.example.com/ajax/validate.php",{
type: request_type,
text: request_text
}, function(data) {
return (data == "valid");
});
}
I realise that this is sort of a "synchronous" call, and that's not what AJAX is about, but I already have numerous functions in validate.php (database calls, etc.) that I can't implement in Javascript, and I saw threads like this onethat talk about using some form of handler.
我意识到这是一种“同步”调用,这不是 AJAX 的意思,但是我在 validate.php 中已经有很多我无法在 Javascript 中实现的函数(数据库调用等),我看到像这样的线程谈论使用某种形式的处理程序。
How would I write a simple handler that will make either the variable data
or the result of the boolean comparison data == "valid"
available when I use it in an if/else
statement (which is where this function is supposed to be used)?
当我在语句中使用变量data
或布尔比较的结果data == "valid"
时,我将如何编写一个简单的处理程序if/else
(这是应该使用此函数的地方)?
EDIT: For example, one of the if
statements that will be using the boolean result:
编辑:例如,if
将使用布尔结果的语句之一:
if (!validate('password',pass_new)) {
$('#pass_new').addClass('error');
$('#pass_confirm_new').addClass('error');
$(error_string.format('Please enter a valid password.')).insertAfter('#pass_confirm_new');
$('#pass_text_short').hide();
$('#pass_text_long').show();
EDIT: The function called with the onsubmit
event in my HTML form:
编辑:onsubmit
在我的 HTML 表单中使用事件调用的函数:
function valid_pass_sett() {
//code to remove errors left over from previous submissions - snipped
pass_old = $('input[name=pass_old]').val();
pass_new = $('input[name=pass_new]').val();
pass_confirm_new = $('input[name=pass_confirm_new]').val();
//some if statements that don't involve AJAX requests - snipped
if (!validate('password',pass_new)) {
$('#pass_new').addClass('error');
$('#pass_confirm_new').addClass('error');
$(error_string.format('Please enter a valid password.')).insertAfter('#pass_confirm_new');
$('#pass_text_short').hide();
$('#pass_text_long').show();
return false;
}
return true;
}
I haven't edited this code to include the updated code that's been posted, but my question is how I return false
from it to stop form submission?
我尚未编辑此代码以包含已发布的更新代码,但我的问题是我如何return false
从中停止表单提交?
回答by hazzik
function validate(request_type, request_text, callback) {
$.post("http://www.example.com/ajax/validate.php",{
type: request_type,
text: request_text
}, function(data) {
callback(data == "valid");
});
}
And usage would be:
用法是:
validate(request_type, request_text, function (isValid) {
if(isValid) {
// do something
} else {
// do something if invalid
}
});
回答by user113716
Unless you make a synchronousAJAX call (which you probably don't want to do), you simply can't.
除非您进行同步AJAX 调用(您可能不想这样做),否则您根本做不到。
If this function is used in several places in your code, your best bet may be to allow it to receivea function.
如果此函数在您的代码中的多个位置使用,最好的办法可能是允许它接收一个函数。
That way instead of relying on the result being returned fromyour function to be used in some code, you're actually passing your code directly in, so it is ensured to be able to use the response.
这样,而不是依赖于从您的函数返回的结果在某些代码中使用,您实际上是直接传递您的代码,因此可以确保能够使用响应。
var my_form = $('#my_form');
my_form.submit( valid_pass_sett );
function valid_pass_sett() {
//code to remove errors left over from previous submissions - snipped
pass_old = $('input[name=pass_old]').val();
pass_new = $('input[name=pass_new]').val();
pass_confirm_new = $('input[name=pass_confirm_new]').val();
validate('password', pass_new, pswd_validation_callback); // async validation
return false; // cancel form submission
}
function validate(request_type, request_text, callback ) {
$.post("http://www.example.com/ajax/validate.php",{
type: request_type,
text: request_text
}, callback );
}
function pswd_validation_callback( data ) {
if ( data === 'valid' ) {
// if valid, call the native .submit() instead of the jQuery one
my_form[ 0 ].submit();
} else {
// Otherwise do your thing for invalid passwords.
// The form has already been canceled, so no concerns there.
$('#pass_new').addClass('error');
$('#pass_confirm_new').addClass('error');
$(error_string.format('Please enter a valid password.')).insertAfter('#pass_confirm_new');
$('#pass_text_short').hide();
$('#pass_text_long').show();
}
}
EDIT:Changed to use code posted in question.
编辑:更改为使用有问题的代码。
EDIT:Updating to work with additional code posted. Narrowing answer down to the named function for clarity.
编辑:更新以使用发布的其他代码。为清楚起见,将答案缩小到命名函数。
回答by pfernandom
function validate(request_type, request_text) {
$.post("http://www.example.com/ajax/validate.php",{
type: request_type,
text: request_text
}, function(data) {
return (data == "valid");
}); }
You can't really return from 'validate' the result of the AJAX call. You could try declare a variable before the $.post call, let's call it 'x', and inside the response function assign the value to that variable (x=data=="valid"), and outside the $.post block, but inside the 'validate' function, return that value.
您无法真正从“验证” AJAX 调用的结果返回。您可以尝试在 $.post 调用之前声明一个变量,让我们称其为“x”,然后在响应函数内部将值分配给该变量 (x=data=="valid"),并在 $.post 块之外,但在“验证”函数内,返回该值。
function validate(request_type, request_text) {
var x;
$.post("http://www.example.com/ajax/validate.php",{
type: request_type,
text: request_text
}, function(data) {
x = data == "valid";
});
return x; }
The real problem is that the function 'validate' will continue even if the post call haven't return any value, so it will always be 'false'.
真正的问题是,即使 post 调用没有返回任何值,函数 'validate' 也会继续,所以它总是为 'false'。
The best thing you can do is call another function INSIDE the response function, so you can assure that the server call is over before getting to the next part.
你能做的最好的事情是在响应函数内部调用另一个函数,这样你就可以确保在进入下一部分之前服务器调用已经结束。
Edit:
编辑:
It's been a long time since I posted this answer. The world has changed and so AJAX calls.
我发布这个答案已经很长时间了。世界已经改变,所以 AJAX 调用。
Now we have promises;)
现在我们有承诺;)
You still cannot return a direct value from a function, but you can return a Promiseobject, which can be chanined to another Promise, and the second promise will get the data you returned from the first one.
您仍然无法从函数返回直接值,但您可以返回一个Promise对象,该对象可以转换为另一个Promise,第二个Promise将获取您从第一个Promise返回的数据。
function validate(request_type, request_text) {
var promise = $.ajax("http://www.example.com/ajax/validate.php",{
type: request_type,
text: request_text
});
function getStuff(data) {
//Do something and return the data to the next promise
return data;
}
promise.then(getStuff).then(function(data){
// Do something else with data
});
}
回答by PowerAktar
If I understand this question correctly you can achieve what you want by simply storing the returned value into a HTML element and then return that elements value from your custom function:
如果我正确理解了这个问题,您可以通过简单地将返回值存储到 HTML 元素中,然后从您的自定义函数返回该元素值来实现您想要的:
function validate(request_type, request_text){
$.post("http://www.example.com/ajax/validate.php",{
type: request_type,
text: request_text},
function(data) {
$('#someElement').text(data);
});
//return the data by getting the value of the html element
return $('#someElement').text();
}