我不能使用ajax从不同的域请求API,这是真的吗?还是我做错了?
我在我不能使用ajax从不同的域请求API,这是真的吗?还是我做错了?,ajax,cors,Ajax,Cors,我在http://www.domain_a.com我需要向托管在http://domain_b.com。现在,当我尝试以下方法时: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> $(do
http://www.domain_a.com
我需要向托管在http://domain_b.com
。现在,当我尝试以下方法时:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON({
url: "http://domain_b.com/service_api/v1/find.json?name=abcd",
dataType: 'json',
beforeSend: setHeader,
success: function(data) {console.log (data)}
});
function setHeader (xhr) {
console.log (xhr);
xhr.setRequestHeader("Authorization", "sdkfhberg83hr87234bf87r432");
console.log (xhr);
}
});
</script>
</head>
<body>
</body>
</html>
我是做错了什么,还是根本不允许(让我吃惊)?跨源资源共享是您想要的。基本上,出于安全原因,同源策略只允许在同一域上运行的脚本访问彼此的DOM。因此,除非您正在调用的API不支持-ie.具有以下响应头-“Access Control Allow Origin”、“*”,否则不允许此调用 对此并不完全确定——但试着利用
此外,它可能对您有用。您正在寻找的是CORS,即跨源资源共享,需要在承载API的域上设置。这是不允许的,除非提供API的服务器设置头以指示允许
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://domain_b/service_api/v1/find.json?name=abcd. This can be fixed by moving the resource to the same domain or enabling CORS.