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.

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

}

1 Comment

Please do provide more details about your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.