使用jQuery从XML文件中正确解析JSON

时间:2011-06-09 20:23:42

标签: jquery xml json

我正在使用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);

2 个答案:

答案 0 :(得分:1)

不知道你得到了什么错误:

$.getJSON('xml.php',function(data) {
    html = '<div class="comments">';
    $.each(data.comment, function(key, comment) {
        var comment_id = comment['@attributes'].id;
        html += '<div class="comment">\n';
        html += '   <span class="name">'+comment.author+'</span>\n';
        html += '</div>';

    });
    html += '</div>';
    $('.comments').replaceWith(html);
});

example

答案 1 :(得分:0)

我不确定您阅读过哪些教程,但{j}模板标记语言(JTML)的take a look at this one