我正在使用这个 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 问题:
http://api.jquery.com/jQuery.getJSON/
http://www.w3schools.com/json/default.asp
当与 W3Schools 的示例相匹配时,语法似乎是正确的。