【问题标题】:Jquery set how to set a global variable json postjquery设置如何设置全局变量json post
【发布时间】:2012-08-06 19:20:54
【问题描述】:

举个例子:

var animal= null;

$.post("ajax.php",{data: data}, function(output){
     animal = output.animal;
},"json");

alert(animal);

原则上,我希望该变量在 ajax 函数的成功回调之外返回一些内容,并在帖子之外声明它。但是它仍然返回“null”。我做错了什么?

【问题讨论】:

  • asynchronous...使用回调函数

标签: jquery variables post callback


【解决方案1】:

因为$.post() 是异步的。所以你不能做你想做的事。取而代之的是,您必须使用如下回调函数:

var animal= null;

$.post("ajax.php",{data: data}, function(data){

     // this callback will execute after
     // after finish the post with
     // and get returned data from server

     animal = data.animal;
     callFunc(animal);
},"json");

function callFunc(animal) {
  alert(animal);
}

【讨论】:

    【解决方案2】:

    问题是警报命令在成功函数之前执行,因为 $.post 根据定义是异步的。

    要做你想做的事,你必须像这样使用同步请求(在请求结束之前代码不会执行):

     var animal = null;
    
     $.ajax({
            url: 'ajax.php',
            async: false,   // this is the important line that makes the request sincronous
            type: 'post',
            dataType: 'json', 
            success: function(output) {
                    animal = output.animal;
                 }
              );
    
      alert(animal);
    

    祝你好运!

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-18
      • 2020-07-23
      • 1970-01-01
      相关资源
      最近更新 更多