从外部站点提取XML数据

时间:2012-02-12 18:12:13

标签: html xml

我正在试图弄清楚如何从我自己网站上没有托管的XML文件中提取数据。我对此完全陌生,所以我不知道我哪里出错了。我可以轻松地从我自己的网站上提取数据。任何帮助将不胜感激,谢谢!

<script type="text/javascript">
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
     xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

  url = "http://elcu.herobo.com/testarea/include/cd_catalog.xml"
  xmlhttp.open("GET",url,false);
  xmlhttp.send();
  xmlDoc=xmlhttp.responseXML;

  document.write("<table border='0' cellpadding='1' cellspacing='1' width'90%' id='1' class='tablesorter'><thead><tr> <th>Artist</th> <th>Title</th> <th>Country</th></thead><tbody>");

  var x=xmlDoc.getElementsByTagName("CD");
  for (i=0;i<x.length;i++)
  {
      document.write("<tr><td>");
      document.write(x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue);
      document.write("</td><td>");
      document.write(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
      document.write("</td><td>");
      document.write(x[i].getElementsByTagName("COUNTRY")[0].childNodes[0].nodeValue);
      document.write("</td></tr>");
  }
  document.write("</tbody></table>");

3 个答案:

答案 0 :(得分:0)

出于安全原因,默认情况下,您不允许执行跨域请求来获取XML数据(same-origin policy)。如果您想跨域获取数据,通常需要使用JSON-P作为格式,或者在您自己的域中设置代理,以便通过它访问数据。

答案 1 :(得分:0)

我以为我永远不会写这个,但是,“你可能会考虑使用jQuery。”它为不同的浏览器提供了所有的支持,并且还支持CORS所需的JSON-P,除非您可以让服务器开始返回CORS头以允许您访问。

答案 2 :(得分:0)

如果您有权访问您的服务器上没有托管的页面(我想您没有),您可以使用JSONP(有关详细信息,请参阅此answer),否则您应该使用PROXY (见answer)。