【问题标题】:Syncrhonous Cross-Domain AJAX request同步跨域 AJAX 请求
【发布时间】: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 requestAccess 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


【解决方案1】:

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

【讨论】:

  • JSONP 不能同步。
  • @Diodeus 看看我刚刚对这个问题所做的编辑。你知道它为什么不工作吗?
【解决方案2】:

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

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

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

【讨论】:

  • 如果我不知道直到运行时会执行多少个 AJAX 请求怎么办? (这取决于用户输入)
  • 然后传递 jqXHR 对象的数组/集合。 $.when.apply($, ajaxRequestArray)
  • 我会在稍后告诉你:)
  • 所以对异步请求的更改有效,但我仍然遇到原始的“访问受限 URI 被拒绝”错误。现在我应该使用 JSONP 吗?
  • @abw333 是的,你应该使用 JSONP。
【解决方案3】:

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

Look at documentation here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多