【问题标题】:Parsing XML using AJAX使用 AJAX 解析 XML
【发布时间】:2017-11-26 17:13:19
【问题描述】:

解析使用时遇到问题。似乎看不出这里出了什么问题,因为我已经能够在我的代码中使用 elsewhere 检索 API。任何帮助将不胜感激。

:

<div id="technology" class="tab-pane fade">
  <h3>TECH</h3>
  <p id="tech_news"></p>
</div>

:

$(document).ready(function() {
  $.ajax({
    type: "GET",
    url: "http://feeds.bbci.co.uk/news/technology/rss.xml",
    dataType: "xml",
    cache: false,
    success: parseXml
  });
});

function parseXml(xml) {
  $(xml).find("item").each(function() {
    $("#tech_news").append($(this).find("title").text() + "<p>");
    $("#tech_news").append($(this).find("description").text() + "<p>");
  });
}

【问题讨论】:

  • 你能分享一下回复吗xml
  • @MuhammadOmerAslam 我不确定你的意思是什么?对不起。
  • 你指定了dataType:"XML",这意味着它返回一个可以通过jQuery处理的XML文档。我说的是那个回复文件
  • @MuhammadOmerAslam XML 文件在上面的 url 中指定。它是来自新闻网站的 RSS 提要。
  • 无法加载feeds.bbci.co.uk/news/technology/rss.xml?_=1511718738881: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access

标签: xml ajax ajax html jquery jquery ajax xml twitter-bootstrap


【解决方案1】:

实际上你有一个issue。我们收到此错误消息:

加载失败 http://feeds.bbci.co.uk/news/technology/rss.xml?_=1511718738881: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

但是您可以使用此服务https://crossorigin.me/ 允许通过 进行跨源请求。

类似这样的:

$(document).ready(function() {
  $.ajax({
    type: "GET",
    url: "https://crossorigin.me/http://feeds.bbci.co.uk/news/technology/rss.xml",
    dataType: "xml",
    cache: false,
    success: parseXml
  });
});

function parseXml(xml) {
  $(xml).find("item").each(function() {
    $("#tech_news").append($(this).find("title").text() + "<p>");
    $("#tech_news").append($(this).find("description").text() + "<p>");
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="technology" class="tab-pane fade">
  <h3>TECH</h3>
  <p id="tech_news"></p>
</div>

即便如此,您应该知道它是一项外部服务,可能无法 24/7 全天候运行。

【讨论】:

  • 谢谢,这对我有用。但是,我很好奇它实际上是如何工作的? crossorigin.me 实际上是做什么的?只是想知道它可以在以后的工作中帮助我:)
  • 不客气。这是一个 CORS 代理。该服务允许开发人员访问其他网站的资源,而无需拥有该网站。只需将“crossorigin.me”添加到响应标头中没有Access-Control-Allow-Origin:* 的任何网址的开头即可。
猜你喜欢
  • 2016-12-20
  • 2014-09-11
  • 1970-01-01
  • 2012-04-30
  • 2010-10-30
  • 2011-10-23
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
相关资源
最近更新 更多