首先,我试图解析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"}]
答案 0 :(得分:1)
尝试这样的事情:
var 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"}]';
var obj = JSON.parse(json);
var content = '<ul>';
$(obj).each(function()
{
var li = '<li id="'+ this.order +'">' + this.question + ' - ' + i.answer + '</li>';
content += li;
});
content += '</ul>';
$('#example').html(content);
答案 1 :(得分:1)
基于jquery.getjson documentation,每个循环应该只使用数据参数:
$.getJSON( "ajax/test.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
另外,我在没有json部分的情况下测试了你的代码,除了i.answer
我更改为i.answer1
并且data.response
更改为data
之外,它工作得很好:
$.each(data, function (item, i) {
items.push('<li id="' + i.order + '">' + i.question + ' - ' + i.answer1 + '</li>');
});