我是jQuery和AJAX的新手,我正在尝试关注代码,只是简单的http get请求。
<html>
<head>
</head>
<body>
<script src = "jquery-2.1.4.js"></script>
<script src = "app.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.get("http://google.com", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>
我收到了以下错误
XMLHttpRequest无法加载http://google.com/。 No&#39; Access-Control-Allow-Origin&#39;标头出现在请求的资源上。 Origin&#39; file://&#39;因此不允许访问。
请帮助我,我错过了什么。
答案 0 :(得分:2)
同源策略不允许您访问托管在其他服务器上的资源。在您的情况下,如果目标系统不在您的控制之下,您可以查看jsonp之类的实用程序,它们可以帮助您解决跨域请求。
答案 1 :(得分:0)
因此根据同源策略的SOP在此策略下,Web浏览器允许第一个Web页面中包含的脚本访问第二个Web页面中的数据,但仅当两个Web页面具有相同的来源时,相同的来源才意味着相同URL方案,主机名和端口号。为了克服这个,你可以使用像
$.ajax({
url: "http://google.com",
dataType: "jsonp"},
success: function( response ) {
console.log( response ); // server response
}
})
阅读有关JSONP的更多信息。
答案 2 :(得分:-1)
这只是您从应用程序中提出的跨域请求,您必须确保避免此错误,
1) Enable cors in your application to make a cross domain application.
2) You can use JSONP while making your request to cross domain instead of GET.
请通过此链接获取有关“CORS”的更多详细信息 https://developers.google.com/api-client-library/javascript/features/cors