【发布时间】:2013-07-25 14:48:06
【问题描述】:
假设如下目录结构:
/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。到目前为止,我已经查看了 Access to restricted URI denied“ code: ”1012 - Cross domain Ajax request 和 Access to restricted URI denied code: 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);
}
});
【问题讨论】:
-
为什么需要同步?为什么不直接延迟执行特定代码,直到触发回调函数?
-
之所以使用AJAX,是因为它是异步的。当你使它同步时,原因就丢失了:(
-
@Vega 我使用 AJAX 的原因是因为它可以加载我的 JSON 数据,而不是因为它是异步的。如果有其他方法也可以加载我的 JSON 数据,我很乐意听到。
-
@Vega 存在同步ajax是唯一解决方案的场景。
-
@abw333 另一种方法是您的 Web 服务器请求 JSON 数据并将其提供给客户端。
标签: javascript jquery ajax json cross-domain