2011-06-09 28 views
0

我正在阅读一个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); 
+1

如果你发布了生成的JSON,它会很有帮助 – 2011-06-09 20:28:40

回答

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

+0

尝试了这一点,并得到“未定义”在html中的适当位置。 – 2011-06-09 20:44:02

+0

如果您没有发布您的JSON,我们无法帮助 – 2011-06-09 20:44:43

+0

对不起,只是更新了原来的帖子。 – 2011-06-09 20:49:23