我正在閱讀一個PHP文件的XML文件,並通過.getJSON調用將其拉入jQuery,但我不知道如何遍歷它。我有以下XML:正確解析通過JSON從XML文件與jQuery
<comments>
<comment id='0'>
<author>John Doe</author>
<datetime>2011-06-05T11:13:00</datetime>
<text>Message text</text>
</comment>
<comment id='1'>
<author>John Doe</author>
<datetime>2011-06-05T11:13:00</datetime>
<text>Message text</text>
</comment>
</comment>
我閱讀,並將它與PHP這樣發送到前端:
$xml = simplexml_load_file("comments.xml");
print json_encode($xml);
它產生的JSON是:
{ "comment" : [
{ "@attributes" : { "id" : "0" },
"author" : "John Doe",
"datetime" : "2011-06-05T11:13:00",
"text" : "Message text"
},
{ "@attributes" : { "id" : "1" },
"author" : "John Doe",
"datetime" : "2011-06-05T11:13:00",
"text" : "Message text"
}
] }
。 ..試圖找出如何在jQuery中操縱它,但沒有太多成功。我一直在閱讀教程和本網站幾個小時,但沒有運氣。我將如何訪問數據?下面是jQuery的:
$.getJSON('xml.php',function(data) {
html = '<div class="comments">';
for (var i=0;i<data.comments;i++){
var obj = data.comments.comment[i];
html += '<div class="comment">\n';
html += ' <span class="name">'+obj.author+'</span>\n';
html += '</div>';
}
html += '</comments>';
$('.comments').replaceWith(html);
});
的想法是產生下面的HTML:
<div class="comments">
<div class="comment first">
<span class="name">Jon Doe</span>
<span class="text">Message Text</span>
<div class="meta">6 minutes ago</div>
</div>
<div class="comment">
<span class="name">John Doe</span>
<span class="text">I hate blue. Can you get add more pink?</span>
<div class="meta">2 hours ago</div>
</div>
</div>
UPDATE 下面是最終的jQuery我放在一起基於答案:
html = '<div class="comments">';
$.each(data.comment, function(key, comment) {
html += ' <div class="comment">\n';
html += ' <span class="name">'+comment.author+'</span>\n';
html += ' <span class="text">'+comment.text+'</span>\n';
html += ' <div class="meta">\n'+comment.datetime+'</div>\n';
html += ' </div>';
});
html += '</div>';
$('.comments').replaceWith(html);
如果你發佈了生成的JSON,它會很有幫助 – 2011-06-09 20:28:40