假设以下目录结构:
/web
example.html
example.js
/example.json
我用浏览器打开 example.html 并运行 example.js,它尝试使用以下调用同步加载 example.json 中的数据:
$.ajax({url: "file:///example.json",
dataType: "json",
async: false,
success: function(data) {
console.log(data)
},
error: function(request, status, error) {
console.log(request);
console.log(status);
console.log(error);
}
});
这会导致错误消息“访问受限 URI 被拒绝”和错误代码 1012。到目前为止,我已经查看了访问受限 URI 被拒绝“代码:”1012 - 跨域 Ajax 请求和访问受限 URI 被拒绝代码: 1012 . 第一个链接建议我使用 jQuery 的getJSON方法,但这种方法只能异步工作。第二个链接建议某种 JSONP 回调,但我无法理解这些究竟是如何工作的。
请注意,如果我将 example.json 移动到 /web/example.json,这个问题很容易消失,但由于我的实际问题的某些情况,我想避免这种情况(我在这里介绍的是对我的实际问题的简化)。
编辑:我正在尝试这个 JSONP 代码,但我仍然遇到同样的错误:
$.ajax({url: "file:///example.json",
dataType: "jsonp",
success: function(data) {
console.log(data)
},
error: function(request, status, error) {
console.log(request);
console.log(status);
console.log(error);
}
});