从$ .post回调返回函数值 [英] return function value from $.post callback

查看:90
本文介绍了从$ .post回调返回函数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

js:

 function verificaExistPed(numped){
        var valida;
        jQuery.post("procedures/class_oc.php", // ajax post
            {
                cache      : false,
                checkYear  : true,
                numped     : numped
            },
            function(data)
            {
                if(data === "s"){
                    valida = true;
                }else{
                    valida = false;
                }
            }
        )
        return valida;
  }

,然后在另一个位置调用该函数,应在变量check(在我的情况下为truefalse)中返回valida结果.

and, calling the function in another place, should return valida result inside variable check, in my case, true or false.

var check = verificaExistPed('".$numped."');
alert(check); // always undifined

但是总是不确定的.

如何从$.post回调中将valida设置为truefalse?

how can i set valida to true or false from a $.post callback ?

推荐答案

由于jQuery.post是异步调用,因此您无法从中返回.您必须依靠回调函数才能从服务器获得响应.试试这个:

You cannot return from as jQuery.post is an asynchronous call. You have to rely on a callback function in order to get the response from server. Try this:

 function verificaExistPed(numped, isValidCallback){
        jQuery.post("procedures/class_oc.php", // ajax post
            {
                cache      : false,
                checkYear  : true,
                numped     : numped
            },
            function(data)
            {
                isValidCallback(data === "s");
            }
        )
  }

用法:

verificaExistPed('".$numped."', function(isValid) {
   alert(isValid); //returns true or false
});

这篇关于从$ .post回调返回函数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆