jQuery Ajax 跨域请求被阻止:同源策略不允许读取远程资源
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23959912/
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
Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource
提问by Newbie
I'm writing a simple site that takes as input an idiom, and return its meaning(s) and example(s) from Oxford dictionary. Here's my idea:
我正在编写一个简单的网站,该网站将一个习语作为输入,并从牛津词典中返回其含义和示例。这是我的想法:
I send a request to the following URL:
我向以下 URL 发送请求:
http://www.oxfordlearnersdictionaries.com/search/english/direct/?q=[idiom]
For example, if the idiom is “not go far”, I'll send a request to:
例如,如果习语是“not go far”,我会发送一个请求到:
http://www.oxfordlearnersdictionaries.com/search/english/direct/?q=not+go+far
And I'll be redirected to the following page:
我将被重定向到以下页面:
http://www.oxfordlearnersdictionaries.com/definition/english/far_1#far_1__192
On this page, I can extract the meaning(s) and the example(s) of the idiom. Here's my code for testing. It will alert the response url:
在此页面上,我可以提取成语的含义和示例。这是我的测试代码。它会提醒响应网址:
<input id="idiom" type="text" name="" value="" placeholder="Enter your idiom here">
<br>
<button id="submit" type="">Submit</button>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").bind('click',function(){
var idiom=$("#idiom").val();
$.ajax({
type: "GET",
url: 'http://www.oxfordlearnersdictionaries.com/search/english/direct/',
data:{q:idiom},
async:true,
crossDomain:true,
success: function(data, status, xhr) {
alert(xhr.getResponseHeader('Location'));
}
});
});
});
</script>
The problem is I've got an error:
问题是我有一个错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.oxfordlearnersdictionaries.com/search/english/direct/?q=by+far. This can be fixed by moving the resource to the same domain or enabling CORS.
跨域请求被阻止:同源策略不允许读取http://www.oxfordlearnersdictionaries.com/search/english/direct/?q=by+far 上的远程资源。这可以通过将资源移动到同一域或启用 CORS 来解决。
Can anybody tell me how to resolve this please? Another approach is fine too
谁能告诉我如何解决这个问题?另一种方法也很好
采纳答案by jsmartfo
Is your website also on the oxfordlearnersdictionaries.com domain? or your trying to make a call to a domain and the same origin policy is blocking you?
您的网站也在 oxfordlearnersdictionaries.com 域上吗?或者您试图拨打某个域并且同源策略阻止了您?
Unless you have permission to set header via CORS on the oxfordlearnersdictionaries.com domain you may want to look for another approach.
除非您有权通过 oxfordlearnersdictionaries.com 域上的 CORS 设置标题,否则您可能需要寻找另一种方法。
回答by G.F.
JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy. JSONP takes advantage of the fact that browsers do not enforce the same-origin policy on script tags. Note that for JSONP to work, a server must know how to reply with JSONP-formatted results. JSONP does not work with JSON-formatted results.
JSONP 或“带填充的 JSON”是一种通信技术,用于在 Web 浏览器中运行的 JavaScript 程序中,用于从不同域中的服务器请求数据,由于同源策略,典型的 Web 浏览器禁止使用这种通信技术。JSONP 利用浏览器不对脚本标签实施同源策略这一事实。请注意,要使 JSONP 工作,服务器必须知道如何使用 JSONP 格式的结果进行回复。JSONP 不适用于 JSON 格式的结果。
http://en.wikipedia.org/wiki/JSONP
http://en.wikipedia.org/wiki/JSONP
Good answer on stackoverflow: jQuery AJAX cross domain
stackoverflow 上的好答案:jQuery AJAX cross domain
$.ajax({
type: "GET",
url: 'http://www.oxfordlearnersdictionaries.com/search/english/direct/',
data:{q:idiom},
async:true,
dataType : 'jsonp', //you may use jsonp for cross origin request
crossDomain:true,
success: function(data, status, xhr) {
alert(xhr.getResponseHeader('Location'));
}
});
回答by AndyPHP
Place below line at the top of the file which you are calling through AJAX.
将下面一行放在您通过 AJAX 调用的文件顶部。
header("Access-Control-Allow-Origin: *");
回答by Raju Singh
We can not get the data from third party website without jsonp.
没有jsonp,我们无法从第三方网站获取数据。
You can use the php function for fetch data like file_get_contents() or CURL etc.
您可以使用 php 函数来获取数据,例如 file_get_contents() 或 CURL 等。
Then you can use the PHP url with your ajax code.
然后你可以在你的 ajax 代码中使用 PHP url。
<input id="idiom" type="text" name="" value="" placeholder="Enter your idiom here">
<br>
<button id="submit" type="">Submit</button>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").bind('click',function(){
var idiom=$("#idiom").val();
$.ajax({
type: "GET",
url: 'get_data.php',
data:{q:idiom},
async:true,
crossDomain:true,
success: function(data, status, xhr) {
alert(xhr.getResponseHeader('Location'));
}
});
});
});
</script>
Create a PHP file = get_data.php
创建一个 PHP 文件 = get_data.php
<?php
echo file_get_contents("http://www.oxfordlearnersdictionaries.com/search/english/direct/");
?>
回答by Shafiq
Add the below code to your .htaccess
将以下代码添加到您的 .htaccess
Header set Access-Control-Allow-Origin *
标头集 Access-Control-Allow-Origin *
It works for me.
这个对我有用。
Thanks
谢谢
回答by Nikhil Gyan
If your website also on the oxfordlearnersdictionaries.com domain, USE the following into the oxfordlearnersdictionaries.com .htaccess file:
如果您的网站也在 oxfordlearnersdictionaries.com 域上,请在 oxfordlearnersdictionaries.com .htaccess 文件中使用以下内容:
Header set Access-Control-Allow-Origin "*"
标头集 Access-Control-Allow-Origin "*"
回答by user1476842
This also need.
这也需要。
<?php
header("Access-Control-Allow-Origin: *");
回答by Arya
I used the header("Access-Control-Allow-Origin: *");
method but still received the CORS error. It turns out that the PHP script that was being requested had an error in it (I had forgotten to add a period (.) when concatenating two variables). Once I fixed that typo, it worked!
我使用了该header("Access-Control-Allow-Origin: *");
方法,但仍然收到 CORS 错误。结果是被请求的 PHP 脚本中有错误(我在连接两个变量时忘记添加句点 (.))。一旦我修正了那个错字,它就奏效了!
So, It seems that the remote script being called cannot have errors within it.
因此,被调用的远程脚本似乎不能有错误。
回答by Vu Tuan Hung
I think setting your header to Access-Control-Allow-Origin: *
would do the trick here. Had the same issue and I resolved it like that.
我认为将您的标题设置为Access-Control-Allow-Origin: *
可以在这里解决问题。有同样的问题,我就这样解决了。
回答by TAHA SULTAN TEMURI
I had the same problem when I was working on asp.net Mvc webApi because cors was not enabled. I solved this by enabling cors inside register method of webApiconfig
我在使用 asp.net Mvc webApi 时遇到了同样的问题,因为 cors 未启用。我通过在 webApiconfig 的 register 方法中启用 cors 解决了这个问题
First install cors from herethen
首先从这里安装 cors 然后
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}