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

The above is my code snippet, I need to store the ajax response datain a global variable dataRsp, but I failed to do this.I am very confuse with the variable scope in JS and jquery.Thank you very much.

stackpop
  • 81
  • 1
  • 11
  • You didn't fail to change it, it's just ***asynchronous*** ! – adeneo Mar 28 '14 at 06:15
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – adeneo Mar 28 '14 at 06:16

2 Answers2

3

Put your alert inside the success callback

    $( 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);
  }

Or Another option would be to add async: false parameter. And also the , after success is not required.

iJade
  • 23,144
  • 56
  • 154
  • 243
  • How to change it if I want the function doAjax return dataRsp, and I need to use the data outside the function.for example, I write x = doAjax(0,0), and then alert x. – stackpop Mar 28 '14 at 06:22
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);

}