gpt4 book ai didi

javascript - 为什么我的 json 引用返回未定义?

转载 作者:行者123 更新时间:2023-11-30 08:08:22 25 4
gpt4 key购买 nike

我正在使用这个 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

与 W3School 的示例匹配时,语法似乎是正确的。

最佳答案

这里有一个额外的=:

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

应该是:

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

你超出了你的数组。

关于javascript - 为什么我的 json 引用返回未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14148569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com