【问题标题】:Local File Html - XMLHttpRequest: Network Error 0x80070005, Access is denied本地文件 Html - XMLHttpRequest:网络错误 0x80070005,访问被拒绝
【发布时间】:2017-08-11 20:54:10
【问题描述】:

编辑:不重复,因为我的问题在提到的每个浏览器上都失败了; Edge、Chrome、FF 等

我有一个 html 文件,该文件将在此人的机器上,而不是在 http 协议上。注意:重要的是它将是个人机器上的 html 文件。

在javascript里面是:

var dataARR = {
    mydata: "No Data"
};

var dataJSON = JSON.stringify(dataARR);
$.support.cors = true;
$.ajax({
    type: "POST",
    url: "http://www.mywebsite.com/exclude.php",
    async: true,
    cache: false,
    contentType: "application/json; charset=utf-8",
    crossDomain: true, // This needs to be true for other people
    data: { myJson: dataJSON },

    success: function (data) {
        var json = eval('(' + data + ')');
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        // Silent error
        var zz = 2;
    }
});

我服务器上的文件http://www.mywebsite.com/exclude.php 是测试的基础。

排除.php

header("Access-Control-Allow-Origin: *"); // To allow cross domain
$arr = ["181K2", "4V419"];
echo json_encode($arr);

如果人的本地机器上的 html 文件是从 Edge、Chrome 等启动的,这不起作用。

Edge 给出错误XMLHttpRequest: Network Error 0x80070005, Access is denied.

Chrome 给出错误XMLHttpRequest cannot load http://www.mywebsite.com/exclude.php. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

Firefox:我不知道如何找到 FF 错误,因为我通常不在 FF 中调试并且不习惯于系统。但是,当我将断点放入时,我最终会出现在 error: function (XMLHttpRequest, textStatus, errorThrown) {

部分

【问题讨论】:

  • crossDomain: true, // This needs to be true for other people — 如果您向 same 源发出请求,然后按照 HTTP 重定向到不同的源,则唯一需要为 true。
  • contentType: "application/json; charset=utf-8", — 您的请求正文未格式化为 JSON。这是错误的。
  • $.support.cors = true; 覆盖 jQuery 对用户 Web 浏览器中的 CORS 支持的检测要么什么都不做,要么破坏。不要那样做。
  • async: true, — 这是默认设置。明确表达是没有意义的。
  • var json = eval('(' + data + ')'); — 这是解析 JSON 的一种糟糕方式……如果服务器输出正确的内容类型,jQuery 将为您解析它。

标签: html ajax xmlhttprequest


【解决方案1】:

Chrome 给出错误 XMLHttpRequest cannot load http://www.mywebsite.com/exclude.php。预检响应中的 Access-Control-Allow-Headers 不允许请求标头字段 Content-Type。

所以要么:

  1. 响应预检请求并允许在请求中包含Content-Type
  2. 不要设置Content-Type

我推荐选项 2,因为您没有将请求正文格式化为 JSON。

【讨论】:

  • 好的,我删除了contentType,我还有更进一步。它现在可以在 Chrome 上运行,但现在在 Edge 上出现以下错误:XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.
猜你喜欢
  • 2015-10-17
  • 2018-04-05
  • 2018-03-11
  • 2019-09-12
  • 2015-01-31
  • 2018-09-07
  • 1970-01-01
  • 2015-09-03
  • 2018-11-22
相关资源
最近更新 更多