简体   繁体   中英

Failed to change a global variable in JQuery ajax function

 $( 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.

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.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM