.getJson没有填充数组

时间:2012-04-06 03:45:49

标签: jquery getjson

我有以下代码:

$(document).ready(function() {
    $.getJSON('../includes/_quiz.php?class_id=163&course_id=183',function(data){
        $.each(data,function(k,v){
            questions[k] = v.question;
            answers[k*4] = v.ansO;
            answers[k*4+1] = v.ansT;
            answers[k*4+2] = v.ansTh;
            answers[k*4+3] = v.ansF;
            });

        //html  
        });
    });

问题数组没有被填充,但是当我调试时,我得到了这个结果: 当我在浏览器中请求页面时,我收到的结果是:

[{"question":"\u0623\u0647\u0645 \u0627\u0644\u0635\u0646\u0627\u0639\u0627\u062a \u0627\u0644\u0633\u0648\u0631\u064a\u0629 \u0648 \u062a\u062f\u062e\u0644 \u0628\u0627\u0644\u062a\u0635\u062f\u064a\u0631 :","ansO":"\u0627\u0644\u0623\u0633\u0645\u062f\u0629","ansT":"\u0627\u0644\u0623\u062f\u0648\u0627\u062a \u0627\u0644\u0632\u0631\u0627\u0639\u064a\u0629","ansTh":"\u0627\u0644\u0632\u064a\u0648\u062a \u0627\u0644\u0646\u0628\u0627\u062a\u064a\u0629","ansF":"\u0627\u0644\u0635\u0646\u0627\u0639\u0627\u062a \u0627\u0644\u0646\u0633\u064a\u062c\u064a\u0629","corr":"4"},{"question":"\u064a\u0633\u062a\u0648\u0631\u062f \u0627\u0644\u0639\u0631\u0627\u0642 \u0628\u0639\u0636 \u0627\u0644\u0645\u0648\u0627\u062f \u0645\u0646\u0647\u0627:","ansO":"\u0627\u0644\u0646\u0641\u0637","ansT":"\u0627\u0644\u062a\u0645\u0648\u0631","ansTh":"\u0627\u0644\u0623\u0644\u0627\u062a","ansF":"\u0627\u0644\u063a\u0627\u0632 \u0627\u0644\u0637\u0628\u064a\u0639\u064a","corr":"3"},{"question":"\u064a\u0628\u0644\u063a \u0639\u062f\u062f \u0633\u0643\u0627\u0646 \u0644\u064a\u0628\u064a\u0627 :","ansO":"\/3.5\/ \u0645\u0644\u064a\u0648\u0646 \u0646\u0633\u0645\u0629","ansT":"\/4\/ \u0645\u0644\u064a\u0648\u0646 \u0646\u0633\u0645\u0629","ansTh":"\/5\/ \u0645\u0644\u064a\u0648\u0646 \u0646\u0633\u0645\u0629","ansF":"\/5.5\/ \u0645\u0644\u064a\u0648\u0646 \u0646\u0633\u0645\u0629","corr":"4"}],

我调试了代码并发现它没有进入内部,它直接移动到最后

在我对代码进行一些修改之前,数组已经填满了, 可能是什么问题?

2 个答案:

答案 0 :(得分:1)

请将数据分配给一个变量

  

Var结果=数据

你只需写一下

  

警报(结果[0] .questions)

您正在获取阵列格式但未分配给任何变量。 首先分配给变量

result = [{"question":"\u0623\u0647\u0645 \u0627\u0644\u0635\u0646\u0627\u0639\u0627\u062a \u0627\u0644\u0633\u0648\u0631\u064a\u0629 \u0648 \u062a\u062f\u062e\u0644 \u0628\u0627\u0644\u062a\u0635\u062f\u064a\u0631 :","ansO":"\u0627\u0644\u0623\u0633\u0645\u062f\u0629","ansT":"\u0627\u0644\u062‌​3\u062f\u0648\u0627\u062a \u0627\u0644\u0632\u0631\u0627\u0639\u064a\u0629","corr":"4"}]

答案 1 :(得分:1)

如果JSON文件包含语法错误,则请求通常会以静默方式失败。所以添加.error方法并检查解析json是否有任何错误

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON("example.json", function() {
  alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });