gpt4 book ai didi

javascript - 浏览器中的 JSON 对象为 null 但不是 Firebug

转载 作者:行者123 更新时间:2023-11-29 16:20:25 24 4
gpt4 key购买 nike

当我在 firebug 中逐步执行此 javascript 代码 (scoreboard.js) 时,它可以很好地处理警报。当我没有在 firebug 中换行并正常运行它时,我收到了一条“favs is null”消息(没有警报)。

var favs = $.getJSON("favs.json");
favs = $.parseJSON(favs.responseText);
favs = favs.myTeams;

for (i=0; i<favs.length; i++){
alert(favs[i].text);
}

JSON (favs.json)

{"myTeams":[{"sport":10,"id":10,"abbrev":"NYY","isFav":false,"text":"New York  Yankees","sw_abbrev":"nyy"},{"sport":28,"id":19,"abbrev":"nyg","isFav":false,"text":"New York Giants","sw_abbrev":"nyg"},{"sport":46,"id":18,"abbrev":"NY","isFav":false,"text":"New York Knicks","sw_abbrev":"nyk"},{"sport":90,"id":11,"abbrev":"NJ","isFav":false,"text":"New Jersey Devils","sw_abbrev":"njd"},{"sport":41,"id":2507,"abbrev":"PROV","isFav":false,"text":"Providence Friars"},{"sport":46,"id":17,"abbrev":"NJ","isFav":false,"text":"New Jersey Nets","sw_abbrev":"njn"},{"sport":600,"id":363,"abbrev":"Blues","isFav":false,"text":"Chelsea","sw_abbrev":"ENG.CHELSEA","isNational":false}]}

HTML

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="scoreboard.js"></script>
</head>

<body>
Test
</body>

知道这里发生了什么吗?

最佳答案

你不需要

favs = $.parseJSON(favs.responseText); 

而且我很确定 $.getJSON() 不会返回 json,而是返回 jqXHR .

查看 parseJSON() 的文档,你可能应该这样做:

jQuery.getJSON( url [, data] [, success(data, textStatus, jqXHR)] )

$.getJSON("favs.json",
function(json)
{
var favs = json.myTeams;

for (i=0; i<favs.length; i++){
alert(favs[i].text);
}
});

$.getJSON() - 成功回调(在我的示例中是匿名函数)传递返回的数据,通常是由 JSON 结构定义并解析的 JavaScript 对象或数组使用 $.parseJSON() 方法。

关于javascript - 浏览器中的 JSON 对象为 null 但不是 Firebug ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10903315/

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