将回调函数(在postrequest中)的值返回到函数内部

return value from callback function (in post request) into the function its inside of?

本文关键字:函数 返回 内部 回调 postrequest      更新时间:2023-09-26

我有一个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");
    });
}

我意识到这是一种"同步"调用,AJAX不是这样的,但我在validate.php中已经有很多函数(数据库调用等(,我无法在Javascript中实现,我看到像这样的线程谈论使用某种形式的处理程序。

当我在if/else语句中使用变量data或布尔比较结果data == "valid"时,我该如何编写一个简单的处理程序(该函数应该在这里使用(?

EDIT:例如,将使用布尔结果的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:在我的HTML表单中用onsubmit事件调用的函数:

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;
}

我还没有编辑此代码以包含已发布的更新代码,但我的问题是如何从中return false来停止表单提交?

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");
    });
}

使用方法是:

validate(request_type, request_text, function (isValid) {
    if(isValid) { 
        // do something
    } else {
        // do something if invalid
    }
});

除非您进行同步AJAX调用(您可能不想这样做(,否则您根本做不到。

如果此函数在代码中的多个位置使用,则最好允许它接收函数。

通过这种方式,您实际上是直接传入代码,从而确保能够使用响应,而不是依赖于函数返回的结果。

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();
    }
}

编辑:更改为使用有问题的发布代码

编辑:更新以使用发布的其他代码。为了清晰起见,将答案缩小到命名函数

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");
}); }

您不能真正从"validate"返回AJAX调用的结果。您可以尝试在$.post调用之前声明一个变量,让我们称之为"x",并在响应函数内部将值分配给该变量(x=data=="validate"(,在$.past块外部,但在"validate'"函数内部,返回该值。

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; }

真正的问题是,即使后调用没有返回任何值,函数"validate"也会继续,因此它总是"false"。

您能做的最好的事情是在响应函数内部调用另一个函数,这样您就可以确保在进入下一部分之前服务器调用已经结束。

编辑:

我已经很久没有发布这个答案了。世界已经改变了,AJAX调用了它。

现在我们有承诺;(

您仍然不能从函数返回直接值,但您可以返回一个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
});
}

如果我正确理解这个问题,只需将返回的值存储到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();
}