javascript 跨域 AJAX 读取 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18279603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cross-Domain AJAX to Read XML
提问by Ben Davidow
Noobie here. I'm writing a client script that needs to read an XML file from another domain. I tried using JSONP. I get a 200 response but the client can't access the returned data for some reason. I get two errors:
诺比在这里。我正在编写一个需要从另一个域读取 XML 文件的客户端脚本。我尝试使用 JSONP。我收到 200 响应,但由于某种原因客户端无法访问返回的数据。我收到两个错误:
Resource interpreted as Script but transferred with MIME type text/xml
and
和
Uncaught SyntaxError: Unexpected token <
Here's the code (I've removed the XML url since it's confidential):
这是代码(我已经删除了 XML url,因为它是机密的):
$(document).ready(function() {
$.getJSON("urlOfFilecallback=?", function(data) {
console.log(data)
})
});
When I try to render the data in the console I get:
当我尝试在控制台中呈现数据时,我得到:
ReferenceError: data is not defined
How can I fix this? Do I need to use a proxy?
我怎样才能解决这个问题?我需要使用代理吗?
回答by Shaunak
You don't have to write your own proxy. You can use YQL if you want to here is an example how:
您不必编写自己的代理。如果你想这里是一个例子,你可以使用 YQL:
//sample site that returns xml
site = 'http://goo.gl/9iQWyG';
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + site + '"') + '&format=xml&callback=?';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON(yql, function(data){
console.log(data.results[0]);
});
here is the jsfiddlecheck console.log.
这是jsfiddle检查 console.log。
(Usage limitsof the public YQL API is 2,000 requests/hour per IP)
(公共 YQL API 的使用限制是每个 IP 每小时 2,000 个请求)
回答by Deepak
XML is not allowed for cross-domain requests by default.
默认情况下,跨域请求不允许使用 XML。
However, with a little server-side programming you can create a proxy and load the data within your own domain, and output it as XML.
但是,通过一些服务器端编程,您可以创建一个代理并在您自己的域中加载数据,并将其输出为 XML。
for more information see this Question
有关更多信息,请参阅此问题
回答by Roger Barreto
If you have access to the other domain side, you could also use this approach Cross Domain Request
如果您可以访问另一个域端,您也可以使用这种方法跨域请求