1

假设以下目录结构:

/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);
    }
});
4

3 回答 3

0

默认情况下不允许跨域 AJAX 请求。您需要使用CORS获得其他服务器的许可,或者您可以使用 JSONP。

于 2013-07-25T14:52:18.807 回答
0

您使用同步 ajax 的理由是错误的。如果您想等到所有 ajax 请求完成,请使用以下方法。

var ajaxRequest1 = $.ajax();
var ajaxRequest2 = $.ajax();
var ajaxRequest3 = $.ajax();
$.when(ajaxRequest1, ajaxRequest2, ajaxRequest3).done(function(){});

这将比在循环内执行一系列同步 ajax 请求更有效/更快。

于 2013-07-25T15:00:25.157 回答
0

跨域请求和 dataType: "jsonp" 请求不支持同步操作。

在此处查看文档。

于 2015-03-08T12:32:27.123 回答