【发布时间】:2013-08-23 22:09:47
【问题描述】:
我正在使用这个 JavaScript:
$.getJSON("/aTest.json", function (jsonObj) {
$("#testJSONBtn").click(function () {
var val = "";
for (var i = 0; i <= jsonObj.events.length; ++i) {
val += jsonObj.events[i].title + ", " + jsonObj.events[i].date + ", " + jsonObj.events[i].explanation + "<br/>";
}
$("#JSONOutput").append(val);
});
});
访问 json 文件:
{
"events":
[
{"title":"Okmulgee Public Schools Starts 3rd Quarter" , "date":"1-2-2013" , "explanation":"Okmulgee Public Schools begins its third quarter."},
{"title":"Okmulgee Public Schools-Closed in Observance of Martin Luther King Jr. Holiday" , "date":"1-21-2013" , "explanation":"The Okmulgee Public Schools will be closed in observance of the Martin Luther King Jr. holiday."},
{"title":"Okmulgee Public Schools County Professional Day" , "date":"2-1-2013" , "explanation":"Okmulgee Public Schools County Professional Day is today."}
]
}
在最终让 IIS Express 提供 json 文件之后,我已经查看了超过一千次的语法并没有看到任何错误,但是当我尝试得到这个时,我得到了:
Uncaught TypeError: Cannot read property 'title' of undefined
这行 JavaScript/jQuery 函数出错:
val += jsonObj.events[i].title + ", " + jsonObj.events[i].date + ", " + jsonObj.events[i].explanation + "<br/>";
我很茫然,我研究了以下网页和 StackOverflow 问题:
Why is my JSON object undefined?
calling Json data returns undefined "
http://api.jquery.com/jQuery.getJSON/
http://www.w3schools.com/json/default.asp
与 W3Schools 的示例相匹配时,语法似乎是正确的。
【问题讨论】:
-
console.log(jsonObj.events[i])返回什么?console.log(jsonObj)怎么样? -
为什么要在 AJAX 成功回调中订阅按钮单击事件处理程序?
-
@Blender 非常抱歉,但我不知道如何获取该信息。
-
@VoidKing:把它放在你的循环中并打开你的 JS 控制台:stackoverflow.com/questions/4743730/…
-
@VoidKing:JS 控制台按钮位于工具栏的最右侧。当您
console.log()脚本中的某些内容时,它会在控制台中弹出:i.imgur.com/cn9tF.png
标签: javascript jquery ajax json