【问题标题】:How do I handle a JSON request that fails when I'm using .ajax and JSONP?当我使用 .ajax 和 JSONP 时,如何处理失败的 JSON 请求?
【发布时间】:2011-10-05 14:53:00
【问题描述】:

我正在编写一个小的 reddit 图片查看应用程序,如果用户输入有效的子 reddit,它可以正常工作。但我正在尝试处理不存在的 reddit 的情况,但无法弄清楚。

function load_data(after) {
    $.ajaxSetup({
        "error": function () {
            // this gets called every time, even for a valid sub-reddit
            location.href = 'index.html';
        }
    });

    fetchUrl = 'http://reddit.com/r/' + subreddit + '.json?jsonp=process_images&after=' + after;

    $.ajax({
        type: "GET",
        url: fetchUrl,
        dataType: "jsonp",
        cycleTime: 1,
        success: process_images
        // error: handle_error <- this doesn't work, because we're using jsonp
        // but if I take out jsonp, my whole app doesn't work any longer, since
        // I'm trying to run it as a local .html file, and cross-site scripting
        // security prevents it
    });
}

load_data(after);

这是来自服务器的响应。但我无法在 .ajax 方法中处理它:

GET http://www.reddit.com/r/%3Blk%3Blkl%3B.json?jsonp=process_images&after=&callback=jQuery1510605472848052159_1310668370375&_=1310668370433 404 (Not Found)

有什么想法吗?

我在这里尝试了一些建议,例如jQuery.getJSON doesn't trigger callback——但它每次都显示基本相同的错误,并带有一些随机数用于“未调用 jQuery#####”。

【问题讨论】:

    标签: jquery ajax error-handling jsonp


    【解决方案1】:

    this answer另一个问题。

    本质上,这是 JQuery 中 jsonp 实现的一个限制。流行的答案是使用this js插件。

    【讨论】:

      【解决方案2】:

      实际上这是跨域脚本注入的一个限制,这是 jQuery 用于 JSONP 的。

      jquery-jsonp plugin 和更新版本的 jQuery 都通过实现超时来解决这个问题。他们仍然无法捕获错误。

      如果可能,更好的解决方案是使用CORS (Cross-Origin Resource Sharing)

      较新版本的 jQuery 支持 CORS,但浏览器和远程站点也必须支持它。

      所有主要桌面浏览器的当前版本都支持 CORS,Internet Explorer 仅从版本 10 开始。

      【讨论】:

        【解决方案3】:

        如果需要,您可以在服务器响应中添加一些标头以允许跨域...

        【讨论】:

        • 您有示例链接吗?
        • 这被称为 CORS,但它只有在远程站点支持时才有效。例如 YQL 支持它,但 Stack Exchange API 不支持。
        【解决方案4】:
        $.ajax({
          statusCode: {
            404: function() {
              //handle the 404 here
              alert('page not found');
            }
          }
        });
        

        这里是参考:http://api.jquery.com/jQuery.ajax/

        编辑

        无法与 jsonp 一起使用,请参阅 ccurrens 的上述答案

        【讨论】:

        • 这不适用于 jsonp,因为 ccurrens 提供的链接指出 jsonp 不提供错误处理,因此 ccurrens 的答案中还提供了一些解决方法...
        猜你喜欢
        • 1970-01-01
        • 2015-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 2014-08-06
        相关资源
        最近更新 更多