Variable scope question in my jQuery

2019-04-09 10:35发布

问题:

I am having a problem with the scope of my variables after having retrieved them from a back-end PHP script as a 2-dimensional JSON array. Here is my code:

var qns, qis, ncs, nzs, tps;

function get_questions() {
    var url = "php/pytania.php";
    $.ajax({
        cache: false,
        type: "GET",
        dataType: "text",
        url: url,
        success: function(response) {
            data = jQuery.parseJSON(response);
            qns = data.qns;
            qis = data.qis;
            ncs = data.ncs;
            nzs = data.nzs;
            tps = data.tps;
        }
    });
}

$(document).ready(function() {
    var index = 0;
    get_questions();
    $("#question_no").text(qns[index]);
});

When I try to reference my qns array in the end, it displays a variable undefined error. It works however within the ajax statement - no problems there...

Thanks and take care! :)

Piotr.

回答1:

The problem is the success method is being called asynchronously - meaning after you have called $().ajax and you try and reference the variable, it has not been assigned yet as the success callback methods hasn't been executed.

This can be solved by setting the async option to false like so:

$.ajax(
   {
      /* this option */
      async: false,
      cache: false,
      type: "GET",
      dataType: "text",
      url: url,
...

This means that nothing else after the ajax call will be executed until you get your response. The alternative to this is placing the code where you need to use the array IN the success callback method itself.



回答2:

Your problem is that you are trying to use the data before it has arrived.

You can add a callback function that you call after the data has come from the server:

var qns, qis, ncs, nzs, tps;

function get_questions(callback) {

   var url = "php/pytania.php"; 

   $.ajax({

      cache: false,
      type: "GET",
      dataType: "text",
      url: url,
      success: function(response) {

         data = jQuery.parseJSON(response);

         qns = data.qns;
         qis = data.qis;
         ncs = data.ncs;
         nzs = data.nzs;
         tps = data.tps;

         callback();

      }

   } );

}

$(document).ready(function() {

   var index = 0;

   get_questions(function(){

     $("#question_no").text(qns[index]);

   });

});

Note: You can use dataType: "json", then the response will be parsed automatically, and you don't have to use parseJSON.



回答3:

You should add a callback function to your ajax request, and try "$( "#question_no" ).text( qns[ index ] );" within the callback function.You try to access the variable before it was actually loaded by the ajax request.