无法在JQuery ajax函数中更改全局变量

时间:2014-03-28 06:13:57

标签: javascript jquery ajax

 $( document ).ready(function() {
        function doAjax( time_from, time_to ){
            var dataRsp;
            $.ajax({
              url: "/query/"+time_from+"/"+time_to,
              type: "GET",
              dataType: "json",
              success: function(data){ dataRsp = data; },
            });
            alert(JSON.stringify(dataRsp));
        };
      doAjax(0,0);
  }

以上是我的代码片段,我需要将ajax响应数据存储为全局变量dataRsp,但我没有这样做。我对JS和jquery中的变量作用域非常困惑。非常感谢。

2 个答案:

答案 0 :(得分:3)

将警报置于成功回调

    $( document ).ready(function() {
        function doAjax( time_from, time_to ){
            var dataRsp;
            $.ajax({
              async: false,
              url: "/query/"+time_from+"/"+time_to,
              type: "GET",
              dataType: "json",
              success: function(data){ 
                  dataRsp = data; 
                  return(JSON.stringify(dataRsp)); 
              }
            });

        };
      var x =doAjax(0,0);
      alert(x);
  }

或另一种选择是添加async: false参数。而且,之后的success也不是必需的。

答案 1 :(得分:0)

// GLOBAL
var dataRsp;
$( document ).ready(function() {
    function doAjax( time_from, time_to ){
        // var dataRsp;
        $.ajax({
          url: "/query/"+time_from+"/"+time_to,
          type: "GET",
          dataType: "json",
          success: function(data){ 
              dataRsp = data; 
              // YOU GET IT HERE
              alert(JSON.stringify(dataRsp)); 
          },
          // Add this if you want to get it just after the "ajax" but not in the callback of "success"
          async: false
        });
        // ALWAYS NULL if async==true as it's not returned yet.
        // alert(JSON.stringify(dataRsp)); 
    };
  doAjax(0,0);

}