2014-03-28 28 views
0
$(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); 
    } 

以上是我的代码片段,我需要存储数据输入一个全局变量dataRsp Ajax响应,但我没能干这事我非常有变量混淆JS和jQuery中的范围。非常感谢。失败在JQuery中的AJAX功能改变一个全局变量

+0

你没有忘记去改变它,它只是*** ***异步! – adeneo

+0

[如何从AJAX调用返回响应?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – adeneo

回答

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之后的,也不是必需的。

+0

如何如果我想要函数doAjax返回dataRsp,则需要更改它,并且我需要使用函数之外的数据。例如,我写x = doAjax(0,0),然后提示x。 – stackpop

+0

@stackpop更新了代码..have一看 – iJade

+0

@stackpop PLZ标记答案,如果它适合你...... – iJade

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

}

+0

请做提供有关你的答案的更多细节。 –