1

I am trying to read, parse and display an xml file using jquery and ajax. but while trying to do that i am getting an error due to which i am not able to parse the xml while

Here is my code.

<!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>

and my xml file is as given below

<?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>

the error that I am getting is

XMLHttpRequest cannot load http://localhost/booklist.xml. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

Now i dont know how to add the access-control-allow-origin for a xml file. If it was php i could have done it but here i am stuck.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Amie james
  • 103
  • 2
  • 8

1 Answers1

2

The error is because the domain making the request does not match the one receiving it. Check the URL you're viewing the site in and make sure that the domain matches, right down to the protocol and port number, so something like http://localhost:8080 for example.

Failing that, you can make the request relative:

$.ajax({
    type: "GET",
    url: "/BookList.xml", // leading slash indicates the URL is relative to the root
    // the rest of your code....
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339