Я читаю XML-файл с помощью PHP и перетаскиваю его в jQuery с помощью вызова .getJSON, но не могу понять, как его перебрать.У меня есть следующий 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);