Ajax设置全局变量,但外部值消失

Ajax sets global vars, but outside the value disappear

本文关键字:外部 消失 设置 全局变量 Ajax      更新时间:2023-09-26

对象窗口上的设置,只获取"固定的";如果我在警报下调用函数[ctrUpadateCount],如果我直接调用,它将不起作用。知道为什么吗?我在另一个项目上也遇到了同样的问题。并且必须应用一个在这里无法应用的解决方案。我试着解释下面的代码。。。抱歉英语不好。

function ctrUpdateCount(idCtrForm)
{     
   $.ajaxSetup({ assync: false});
   tableName= 'clients';
   p_comando="select count(*) total from "+tableName;
   $.post("execute.php", {comando : p_comando}, function(json){           
    v_total=json[1].total ; // <= this retuns 3
    window['ctrBuffer_'+idCtrForm].count=v_total;
    alert("count inside = "+ window['ctrBuffer_'+idCtrForm].count );//this alerts 3
   },'json'); 
}
jQuery.fn.extend( { ctrLoad: function()
   { 
    if( $(this).get(0).tagName =='FORM'){       
     idCtrForm=$(this).attr('id');
     alert("direct count ="+ctrUpdateCount(idCtrForm) ); // this will alert 3
                                                         // and so  the next alert
     //teste=ctrUpdateCount(idCtrForm); // but if I use this, 
                                        //the next alert will show  "undefined"
     alert("count after = "+ window['ctrBuffer_'+idCtrForm].count );
    }
  } 
})

您的"ctrUpdateCount"函数正在使用$.post(),它是异步的。不可能让函数返回由异步操作的结果确定的值;它本质上是荒谬的。

我真的不知道你想做什么,但基本上你必须对$.post()的回调函数内部的"POST"操作结果做你需要做的事情。