Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从jQuery ajax调用分配responseText时出现问题_Jquery_Ajax - Fatal编程技术网

从jQuery ajax调用分配responseText时出现问题

从jQuery ajax调用分配responseText时出现问题,jquery,ajax,Jquery,Ajax,我一直在开发一个简单的测试程序。代码中嵌入的JSON allQuestions对象一切正常。现在我想将allQuestions对象从索引文件中移出,放入test.json,并通过jQuery AJAX调用检索它 我假设我需要将allQuestions保留为一个全局变量,因为我在脚本中的其他位置操作它 我第一次在脚本中遇到“allQuestions为空错误” 尝试将其声明为数组,但我得到一个allQuestions未定义异常。这是嵌入JSON的版本(很抱歉,我还没有弄清楚如何在JSFIDLE中使用

我一直在开发一个简单的测试程序。代码中嵌入的JSON allQuestions对象一切正常。现在我想将allQuestions对象从索引文件中移出,放入
test.json
,并通过jQuery AJAX调用检索它

我假设我需要将allQuestions保留为一个全局变量,因为我在脚本中的其他位置操作它

我第一次在脚本中遇到“allQuestions为空错误”

尝试将其声明为数组,但我得到一个allQuestions未定义异常。这是嵌入JSON的版本(很抱歉,我还没有弄清楚如何在JSFIDLE中使用AJAX函数性)。当我注释掉json并替换时:

var allQuestions = null;
    // jQuery AJAX request to read JSON formatted Test Questions & Answers from file
     $.ajax({
        url: "test.json",
        dataType: "json",
        success: function(result) {
           allQuestions = result;
        }
      });
我通过firebug看到我得到的响应正常:

[{
    question: ["Who is Prime Minister of the United Kingdom?", "Who is the Vice-President of the United
 States?", "Who is Chancellor of Germany?", "Who is the Prime Minister of Canada?"],
    choices: [
      ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
      ["Barack Obama", "Bernie Sanders", "Nancy Pelosi", "Joe Biden"],
      ["Franz Ritz", "Angela Merkel", "Jan Schroeder", "John Stevens", "Karl Marx"],
      ["Wayne Gretsky", "Pierre Trudeau", "Mike Myers", "Justin Trudeau", "Justin Bieber"]
    ],
    correctAnswer: [0, 3, 1, 3]
  }]
但所有问题都是空的。我似乎根本无法进入success函数,因为当我使用断点一步一步地遍历它时,它会直接遍历success选项并返回。我甚至试着只做一个提醒(结果),但没有成功(没有双关语)


任何洞察都将不胜感激

您可能缺少的一点是AJAX调用是异步的

因此发生的情况是:

- you initialize allQuestions
- you *start* requesting allQuestions to the server
- you render the page, and allQuestions is still NULL
- the server replies, but now it's too late.
那你是做什么的?将渲染函数放置在AJAX成功函数中:

$.post(..., function(reply) {
    allQuestions = reply;
    renderOnPage(allQuestions);
});

您可能会发现,这种方法不再要求所有问题都是全局性的,所有相关函数只需在它们之间传递它。

尝试将键用双引号括起来,如“问题”、“选择”等,放入test.json中。要验证OP将
警报(结果)放在哪里会很有趣
你的意思是我必须我必须把我所有的函数,如check-answer、button\u render和on()函数都放在success中?我把alert作为success选项中唯一的一行。我很困惑。为什么要使用$.post。我只想从服务器上获取json文件,然后将响应存储在变量中。我不明白你的例子。这是我所问的关于成功实现所有功能的速记。所以,成功就像是整个脚本的包装器?我看到您使用$.post作为速记ajax功能。但是renderOnPage(所有问题)应该做什么呢?