【发布时间】:2013-09-15 00:00:38
【问题描述】:
我想制作一个使用来自另一个域的 xml 数据的小型网站。 (来自 Weather Underground 的天气数据:www.wunderground.com)。我只使用 html 和 javascript,并在 Visual Studio Express 2012 for Web 中全部编写。
我按如下方式发出并发送 xml 请求:
url = "http://api.wunderground.com/api/3c6e3d838e217361/geolookup/conditions/forecast/q/51.11999893,-114.01999664.xml";
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
问题是我在 Google Chrome(版本 29.0.1547.66)开发者控制台中收到以下错误:
XMLHttpRequest cannot load http://api.wunderground.com/api/3c6e3d838e217361/geolookup/conditions/forecast/q/51.11999893,-114.01999664.xml. Origin http://localhost:49933 is not allowed by Access-Control-Allow-Origin.
或者在 Internet Explorer(版本 10.0.8)控制台上:
SEC7118: XMLHttpRequest for http://api.wunderground.com/api/3c6e3d838e217361/geolookup/conditions/forecast/q/51.11999893,-114.01999664.xml required Cross Origin Resource Sharing (CORS).
据我了解,CORS (http://enable-cors.org/) 需要客户端和服务器双方的努力才能工作。我想假设 Weather Underground API 知道它在做什么并且已经适当地启用了一些东西,例如将响应标头设置为包含“Access-Control-Allow-Origin:*”,并且我知道我遇到同样的问题时我使用另一个 API 提供程序(World Weather Online)尝试相同的代码。所以我认为这是我应该能够在我的客户端代码中解决的问题。 另一个建议是修复服务器端标头的SO答案: CORS with XMLHttpRequest
我试图找到答案,但不理解以下文章: http://dev.opera.com/articles/view/dom-access-control-using-cross-origin-resource-sharing/ http://saltybeagle.com/2009/09/cross-origin-resource-sharing-demo/
【问题讨论】:
-
你检查了他们设置的标题吗?
-
我直接在 Chrome 中打开你的 url,开发者工具告诉我没有返回
Access-Control-Allow-Origin标头。 -
开发规则 1:不要假设其他人所做的事情是为了让您的生活更轻松。查看他们的 API 文档。 JSON、XML 和 JSONP - 带有示例。没有提到CORS。使用 JSONP。
-
@Passerby 谢谢,我不知道你能做到。
标签: javascript xmlhttprequest cors