【发布时间】:2014-11-07 16:27:02
【问题描述】:
首先,我正在尝试解析 JSON,并且在本地使用文件。
当我运行以下命令时:
$.getJSON('/trivia_demos.json', function(data) {
alert("It worked!); });
警报框出现,我可以确认我在本地调用了正确的文件。 Console.log 也可以。到目前为止,一切都很好。
我现在想提取数据的几个部分并在页面上显示它们。 JSFiddle 在这里,但相关代码如下:
$.getJSON('/trivia_demos.json', function(data) {
var items = []
$.each(data.reponse, function(item, i) {
items.push('<li id="' + i.order + '">' + i.question + ' - ' + i.answer + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('#example');});
实际上,我希望将顺序、问题和答案附加到我的 div“#example”。当我加载页面时,没有任何反应。鉴于我的第一点,我相信我正在搞砸 JQuery 的构建,以针对这三个数据并显示它们。
我相信在调用 json 文件和实际访问 json 对象之间缺少一些东西。
此外,在 trivia_demos.json 文件中,存在以下 json。
[{"id":1,"order":1,"question":"Who was the only American President to
learn English as a second language? ","answer1":"John Quincy Adams",
"answer2":"Martin van Buren","answer3":"William McKinley ",
"answer4":"Andrew Jackson","correcta":"Martin van Buren",
"published":"2014-11-04","url":"http://example.com/trivia_demos/1.json"}]
【问题讨论】:
-
您的 jsFiddle 示例不起作用,因为您没有在页面上包含 jQuery。如果您打开浏览器的开发人员工具,您将看到一条错误消息,指出“Uncaught ReferenceError: $ is not defined”。使用页面左侧的下拉菜单包含适当的库(例如 jQuery)。
-
$.getJSON是异步。这意味着当您将项目附加到ul元素时,异步操作可能尚未完成
标签: javascript json