在我的jQuery的变量范围的问题 [英] Variable scope question in my jQuery

查看:122
本文介绍了在我的jQuery的变量范围的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有检索它们从后端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.

这篇关于在我的jQuery的变量范围的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆