我从ASP.NET表单中调用这个函数,在调用Ajax时在firebug控制台中得到以下错误。
跨源请求被阻止:同一源策略不允许读取http://anotherdomain/test.json上的远程资源。(原因:CORS标头“Access-Control-Allow-Origin”丢失)。
var url= 'http://anotherdomain/test.json';
$.ajax({
url: url,
crossOrigin: true,
type: 'GET',
xhrFields: { withCredentials: true },
accept: 'application/json'
}).done(function (data) {
alert(data);
}).fail(function (xhr, textStatus, error) {
var title, message;
switch (xhr.status) {
case 403:
title = xhr.responseJSON.errorSummary;
message = 'Please login to your server before running the test.';
break;
default:
title = 'Invalid URL or Cross-Origin Request Blocked';
message = 'You must explictly add this site (' + window.location.origin + ') to the list of allowed websites in your server.';
break;
}
});
我做了其他的方法,但仍然找不到解决办法。
注意:我没有服务器权限进行服务器端(API/URL)更改。
当您尝试访问另一个域的资源时,通常会发生这种情况。
这是一个安全特性,可以避免每个人自由访问该域的任何资源(例如,可以在盗版域上访问与您的网站完全相同的副本)。
响应的头,即使是200OK,也不允许其他源(域、端口)访问resources。
如果您是两个域的所有者,则可以修复此问题:
若要更改,您可以在请求的域文件的.htaccess中写入以下内容:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
如果您只想授予对一个域的访问权限,那么.htaccess应该如下所示:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin 'https://my-domain.tdl'
</IfModule>
如果您将此设置到所请求文件的响应头中,您将允许每个人访问resSources:
Access-Control-Allow-Origin : *
或
Access-Control-Allow-Origin : http://www.my-domain.com
和平与守则;)