Ajax 跨源请求被阻止:同源策略不允许读取远程资源

问题描述 投票:0回答:12

我正在编写一个简单的网站,它以习语作为输入,并从牛津词典返回其含义和示例。这是我的想法:

我向以下 URL 发送请求:

http://www.oxfordlearnersdictionaries.com/search/english/direct/?q=[idiom]

例如,如果成语是“not go far”,我会发送请求到:

http://www.oxfordlearnersdictionaries.com/search/english/direct/?q=not+go+far

我将被重定向到以下页面:

http://www.oxfordlearnersdictionaries.com/definition/english/far_1#far_1__192

在这个页面上,我可以提取该成语的含义和示例。
这是我的测试代码。它将提醒响应 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>

问题是我有一个错误:

跨源请求被阻止:同源策略不允许读取 http://www.oxfordlearnersdictionaries.com/search/english/direct/?q=by+far 处的远程资源。这可以通过将资源移动到同一域或启用 CORS 来解决。

有人可以告诉我如何解决这个问题吗?
另一种方法也很好。

jquery ajax cross-domain
12个回答
29
投票

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'));
  }
});

19
投票

将以下行放在您通过 AJAX 调用的文件顶部。

header("Access-Control-Allow-Origin: *");

11
投票

如果没有jsonp,我们无法从第三方网站获取数据。

您可以使用 php 函数来获取数据,例如 file_get_contents() 或 CURL 等

然后您可以将 PHP url 与您的 ajax 代码一起使用。

<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>

创建 PHP 文件 = get_data.php

<?php
  echo file_get_contents("http://www.oxfordlearnersdictionaries.com/search/english/direct/");
?>

10
投票

您的网站也在 oxfordlearnersdictionaries.com 域上吗?或者您尝试调用某个域,但同源策略阻止了您?

除非您有权通过 oxfordlearnersdictionaries.com 域上的 CORS 设置标头,否则您可能需要寻找其他方法。


8
投票

将这些添加到您的 ajax url 调用的 php 文件中

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");

4
投票

将以下代码添加到您的.htaccess

标头设置 Access-Control-Allow-Origin *

它对我有用。

谢谢


3
投票

如果您的网站也在 oxfordlearnersdictionaries.com 域上,请在 oxfordlearnersdictionaries.com .htaccess 文件中使用以下内容:

<IfModule mod_headers.c>
  Header set Access-Control-Allow-Origin "*"
</IfModule>

1
投票

这个也需要。

<?php
header("Access-Control-Allow-Origin: *");

1
投票

我使用了

header("Access-Control-Allow-Origin: *");
方法,但仍然收到CORS错误。事实证明,所请求的 PHP 脚本中有一个错误(我忘记在连接两个变量时添加句点 (.))。一旦我修正了这个错字,它就成功了!

所以,看来被调用的远程脚本中不能有错误。


0
投票

我认为将标题设置为

Access-Control-Allow-Origin: *
就可以了。有同样的问题,我就这样解决了。


0
投票

我在使用asp.net Mvc webApi时遇到了同样的问题,因为cors没有启用。 我通过在 webApiconfig 的注册方法中启用 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 }
  );
}

0
投票

更安全的使用方式

Access-Control-Allow-Origin: https://myrequestingwebsite.com

有一篇不错的文章这里

避免使用

Access-Control-Allow-Origin: *
你会暴露给所有人

© www.soinside.com 2019 - 2024. All rights reserved.