我收到访问控制错误
为什么我在尝试读取远程 xml feed 时会收到此错误?
XMLHttpRequest cannot load http://www.companyname.com/external.php?type=xml. Origin http://intranet is not allowed by Access-Control-Allow-Origin.
这是我用来尝试获取 xml 文件的脚本:
$(document).ready(function() {
get_xml_feed();
function get_xml_feed() {
$.ajax({
url: 'http://www.companyname.com/external.php?type=xml',
type: 'GET',
dataType: 'xml',
error: function(xhr, status, error) {
console.log(status);
console.log(xhr.responseText);
},
success: function(xml) {
$(xml).find('items').each(function(){
var id = $(this).attr('guid');
var title = $(this).find('title').text();
var date = $(this).find('pubDate').text();
var url = $(this).find('link').text();
$('.divContent').empty().append(title + " - " + date + " - " + url + "<br />");
});
}
});
}
});
Why am I getting this error when trying to read a remote xml feed?
XMLHttpRequest cannot load http://www.companyname.com/external.php?type=xml. Origin http://intranet is not allowed by Access-Control-Allow-Origin.
This is the script I am using to try to get the xml file:
$(document).ready(function() {
get_xml_feed();
function get_xml_feed() {
$.ajax({
url: 'http://www.companyname.com/external.php?type=xml',
type: 'GET',
dataType: 'xml',
error: function(xhr, status, error) {
console.log(status);
console.log(xhr.responseText);
},
success: function(xml) {
$(xml).find('items').each(function(){
var id = $(this).attr('guid');
var title = $(this).find('title').text();
var date = $(this).find('pubDate').text();
var url = $(this).find('link').text();
$('.divContent').empty().append(title + " - " + date + " - " + url + "<br />");
});
}
});
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为您违反了同源政策。 AJAX 请求只能发送到与托管脚本的网址属于同一域的网址。
典型的解决方法包括在您的域上设置一个服务器端脚本,该脚本将充当您的域和远程域之间的桥梁,然后向该委托脚本发送 AJAX 请求。
另一种可能性是使用 JSONP 但这远程域必须支持它。
Because you are violating the same origin policy. AJAX requests can be sent only to urls belonging on the same domain as the one hosting your script.
Typical workaround consist of setting up a server side script on your domain that will act as a bridge between your domain and the remote domain and then send an AJAX request to this script that will delegate.
Another possibility is to use JSONP but this the remote domain must support it.