我下面的代码运行良好,但我需要从 xml URL 而不是像这样从 HTML 文件导入 XML 数据 如果我需要从 XML 中检索图像,我该怎么做。
var xml = "<shows><show><date>9/8</date><place>Toads Place</place><location>New Haven, CT</location><time>9PM</time></show></shows>"
$(document).ready(function(){
//$('#table').append('<h2>SHOWS</h2>');
$('#table').append('<table id="show_table">');
$(xml).find('show').each(function(){
var $show = $(this);
var date = $show.find('date').text();
var place = $show.find('place').text();
var location = $show.find('location').text();
var time = $show.find('time').text();
var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr>';
$('#show_table').append(html);
});
//alert($('#show_table').html());
})
我需要做的就是改变这个 var xml = "9/8 ... "让 JQuery 代码从在线 URL 读取
最佳答案
如果需要从URL中加载XML数据,需要执行AJAX请求,可能是这样的:
$(function() {
$.ajax({
type: "get",
url: "http://yoursite.com/yourfile.xml",
dataType: "xml",
success: function(data) {
/* handle data here */
$("#show_table").html(data);
},
error: function(xhr, status) {
/* handle error here */
$("#show_table").html(status);
}
});
});
请记住,如果您使用 AJAX,您可以将 .xml 文件放在同一个域名上。在其他情况下,您需要设置跨源资源共享
(CORS)。
已编辑:
我修改了您的代码,现在它将 td
元素附加到您的表中。但是 xml 仍然在 html 中。
var xml = "<shows><show><date>9/8</date><place>Toads Place</place><location>New Haven, CT</location><time>9PM</time></show></shows>"
$(function() {
$(xml).find('show').each(function() {
console.log(this);
var $show = $(this);
var date = $show.find('date').text();
var place = $show.find('place').text();
var location = $show.find('location').text();
var time = $show.find('time').text();
var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr>';
$('#show_table').append($(html));
});
});
但是你需要修改你的html文件,在这里查看我的解决方案:http://jsfiddle.net/a4m73/
已编辑:从 URL 加载 xml 的完整解决方案
我结合了上面描述的两个部分,在这里查看:http://jsfiddle.net/a4m73/1/
关于javascript - jQuery 读取 XML URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21508343/