Ajax跨源请求被阻止:同源策略不允许读取远程资源
我正在写一个简单的网站,作为输入成语,并从牛津词典中返回其含义和示例。 这是我的想法:
我向以下url发送请求:
http://www.oxfordlearnersdictionaries.com/search/english/direct/?q=[idiom]
例如,如果成语“不走远”,我会发送一个请求:
http://www.oxfordlearnersdictionaries.com/search/english/direct/?q=not+go+far
我将被重定向到以下页面:
http://www.oxfordlearnersdictionaries.com/definition/english/far_1#far_1__192
在这个页面上,我可以提取成语的含义和例子。 这是我的测试代码。 它会提醒响应url:
$(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')); } }); }); });
问题是我有一个错误:
跨源请求已阻止:同源策略不允许在http://www.oxfordlearnersdictionaries.com/search/english/direct/?q=by+far上读取远程资源。 这可以通过将资源移动到同一域或启用CORS来解决。
谁能告诉我如何解决这个问题? 另一种方法也很好
您的网站也在oxfordlearnersdictionaries.com域名吗? 或者您试图拨打域名并且相同的原始政策会阻止您?
除非您有权通过oxfordlearnersdictionaries.com域上的CORS设置标头,否则您可能希望寻找其他方法。
JSONP或“带填充的JSON”是在Web浏览器中运行的JavaScript程序中使用的通信技术,用于从不同域中的服务器请求数据,这是典型Web浏览器因同源策略而禁止的。 JSONP利用了浏览器不对脚本标记实施同源策略的事实。 请注意,要使JSONP正常工作,服务器必须知道如何使用JSONP格式的结果进行回复。 JSONP不适用于JSON格式的结果。
http://en.wikipedia.org/wiki/JSONP
stackoverflow的好答案: jQuery AJAX跨域
$.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')); } });
没有jsonp,我们无法从第三方网站获取数据。
您可以使用php函数获取数据,如file_get_contents()或CURL等。
然后你可以将PHP url与你的ajax代码一起使用。
创建一个PHP文件= get_data.php
将下面的行放在您通过AJAX调用的文件的顶部。
header("Access-Control-Allow-Origin: *");
将以下代码添加到.htaccess
标题集Access-Control-Allow-Origin *
这个对我有用。
谢谢
当我在asp.net Mvc webApi上工作时,我遇到了同样的问题,因为没有启用cors。 我通过在webApiconfig的register方法中启用cors来解决这个问题
首先从这里安装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 } ); }