【发布时间】:2011-06-09 20:23:42
【问题描述】:
我正在使用 PHP 读取 xml 文件并通过 .getJSON 调用将其拉入 jQuery,但我不知道如何对其进行迭代。我有以下 XML:
<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>
更新 这是我根据答案整理的最终 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 会很有帮助