如何使用jquery和ajax读取、解析和显示XML

how to read, parse and display an xml using jquery and ajax

本文关键字:显示 XML 读取 何使用 jquery ajax      更新时间:2023-09-26

我正在尝试使用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'标头。因此,不允许访问原点'null'。

现在我不知道如何为xml文件添加access-control-allow-origin。如果是php,我可以这样做,但这里我卡住了

这个错误是因为发出请求的域与接收请求的域不匹配。检查您正在查看网站的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....