为什么我的json引用返回undefined?

时间:2013-01-03 22:51:43

标签: javascript jquery ajax json

我正在使用此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?

JSON returning as undefined

calling Json data returns undefined "

http://api.jquery.com/jQuery.getJSON/

http://www.w3schools.com/json/default.asp

当与W3Schools的例子匹配时,语法似乎正确。

1 个答案:

答案 0 :(得分:6)

你在这里有一个额外的=:

for (var i = 0; i <= jsonObj.events.length; ++i) {

应该是:

for (var i = 0; i < jsonObj.events.length; ++i) {

你正在超越阵列。