【发布时间】: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