【发布时间】:2015-06-04 07:11:11
【问题描述】:
我正在尝试使用 jquery 和 ajax 读取、解析和显示 xml 文件。但是在尝试这样做时,我遇到了一个错误,因此我无法解析 xml 而
这是我的代码。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("#dvContent").append("<ul></ul>");
$.ajax({
type: "GET",
url: "http://localhost/BookList.xml",
dataType: "xml",
success: function(xml){
$(xml).find('Book').each(function(){
var sTitle = $(this).find('Title').text();
var sPublisher = $(this).find('Publisher').text();
$("<li></li>").html(sTitle + ", " + sPublisher).appendTo("#dvContent ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
</script>
<style type="text/css">
body
{
font-family : Arial;
font-size : 10pt;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="dvContent">
</div>
</form>
我的 xml 文件如下所示
<?xml version="1.0" encoding="utf-8"?>
<BookList>
<Book>
<Title>jQuery: Novice to Ninja</Title>
<Publisher>Site point</Publisher>
</Book>
<Book>
<Title>Learning jQuery</Title>
<Publisher>PACKT</Publisher>
</Book>
<Book>
<Title>Head First jQuery</Title>
<Publisher>O'Reilly</Publisher>
</Book>
<Book>
<Title>jQuery UI 1.8</Title>
<Publisher>PACKT</Publisher>
</Book>
</BookList>
我得到的错误是
XMLHttpRequest 无法加载 http://localhost/booklist.xml。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'null'。
现在我不知道如何为 xml 文件添加访问控制允许来源。如果是 php,我本可以做到的,但在这里我被卡住了。
【问题讨论】:
-
在浏览器中输入
http://localhost/BookList.xml并找到获取xml? -
@ozil 我得到了 xml..using 该链接,但我无法解析和显示
标签: javascript jquery ajax xml