【发布时间】:2023-03-20 14:55:01
【问题描述】:
我一直在尝试获取 Digg rss 提要并将其内容解析为表格,作为使用 jQuery / XML 的介绍。我以this webmonkey 为例并尝试对其进行自定义。这是我的js文件:
// File: readXML.js
// Start function when DOM has completely loaded
$(document).ready(function(){
// Open the students.xml file
$.get("digg.com/rss/index.xml",{},function(xml){
// Build an HTML string
myHTMLOutput = '';
myHTMLOutput += '<table width="98%" border="1" cellpadding="0" cellspacing="0">';
myHTMLOutput += '<th>Title</th><th>PubDate</th><th>Description</th><th>Link</th>';
// Run the function for each student tag in the XML file
$('item',xml).each(function(i) {
diggTitle = $(this).find("title").text();
diggDate = $(this).find("pubDate").text();
diggDesc = $(this).find("description").text();
diggLink = $(this).find("link").text();
// Build row HTML data and store in string
mydata = BuildDiggHTML(diggTitle,diggDate,diggDesc,diggLink);
myHTMLOutput = myHTMLOutput + mydata;
});
myHTMLOutput += '</table>';
// Update the DIV called Content Area with the HTML string
$("#ContentArea").append(myHTMLOutput);
});
});
function BuildDiggHTML(diggTitle,diggDate,diggDesc,diggLink){
// Build HTML string and return
output = '';
output += '<tr>';
output += '<td>'+ diggTitle +'</td>';
output += '<td>'+ diggDate +'</td>';
output += '<td>'+ diggDesc +'</td>';
output += '<td>'+ diggLink +'</td>';
output += '</tr>';
return output;
}
还有我的 HTML:
<html>
<head>
<title>JQuery Easy XML Read Example</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="readXML.js"></script>
</head>
<body>
<div id="ContentArea"></div>
</body>
</html>
基本上,它不起作用:它只是打印没有任何数据的表头。 (我在修改之前检查了示例和代码,它工作得很好。)那么,基本上,我哪里出错了??
编辑
这是由 andres 提供的新代码(仍然无法正常工作!)
// File: readXML.js
// Start function when DOM has completely loaded
$(document).ready(function(){
// Open the students.xml file
$.get("http://feeds.digg.com/digg/popular.rss",{},function(xml){
// Build an HTML string
myHTMLOutput = '<table width="98%" border="1" cellpadding="0" cellspacing="0">';
myHTMLOutput += '<thead><th>Title</th><th>PubDate</th><th>Description</th><th>Link</th></thead>';
// Run the function for each student tag in the XML file
myHTMLOutput += '<tbody>'
$('item',xml).each(function(i) {
// Build row HTML data and store in string
myHTMLOutput += BuildDiggHTML(this);
});
myHTMLOutput += '</tbody></table>';
// Update the DIV called Content Area with the HTML string
$("#ContentArea").append(myHTMLOutput);
});
});
function BuildDiggHTML(el){
// Build HTML string and return
var output = '';
output = '<tr>';
try {
output += '<td>'+ $(el).find("title").text() +'</td>';
output += '<td>'+ $(el).find("pubDate").text() +'</td>';
output += '<td>'+ $(el).find("description").text() +'</td>';
output += '<td>'+ $(el).find("link").text() +'</td>';
}catch(ex){
output = '<td colspan="4">'+ex.description+'</td>';
}
output += '</tr>';
return output;
}
【问题讨论】: