【问题标题】:how to read, parse and display an xml using jquery and ajax [duplicate]如何使用 jquery 和 ajax 读取、解析和显示 xml [重复]
【发布时间】: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


【解决方案1】:

错误是因为发出请求的域与接收请求的域不匹配。检查您正在查看站点的 URL,并确保域匹配,直到协议和端口号,例如 http://localhost:8080

如果做不到这一点,您可以使请求相对:

$.ajax({
    type: "GET",
    url: "/BookList.xml", // leading slash indicates the URL is relative to the root
    // the rest of your code....

【讨论】:

  • 我也试过这个。它不工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
  • 2011-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多