在我的jQuery的变量范围的问题我的、变量、范围、问题

2023-09-10 17:57:56 作者:念来过倒别你叫

我有检索它们从后端PHP脚本作为一个二维JSON数组后有我的变量的作用域的问题。这是我的code:

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

当我尝试引用我QNS阵,最终,它会显示一个变量未定义的错误。它的工作原理然而,AJAX语句中 - 有没有问题...

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

感谢和照顾! :)

彼得。

推荐答案

现在的问题是成功的方法被称为异步 - 这意味着你已经被称为后$()Ajax和你尝试引用该变量,它没有被尚未分配的成功回调方法还没有被执行。

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.

这可以通过异步选项设置为false,像这样来解决:

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,
...

这意味着,不出意外的Ajax调用后会被执行,直到你得到你的回应。的替代,这是放置code,你需要使用数组中的成功回调方法本身。

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.

 
精彩推荐
图片推荐