jquery - 当我使用 .ajax 和 JSONP 时,如何处理失败的 JSON 请求?

标签 jquery ajax error-handling jsonp

我正在编写一个小型 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##### 未调用”。

最佳答案

看看this answer另一个问题。

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

关于jquery - 当我使用 .ajax 和 JSONP 时,如何处理失败的 JSON 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6698426/

相关文章:

javascript背景水平/垂直滚动到元素站点:beyond 911

C - 允许函数显示遇到错误的正确格式是什么?

jquery - 添加 jQuery 监听器会降低浏览器性能吗?

php - 在 WooCommerce 中跟踪添加到购物车并提交 Facebook Pixel 订单

java - 处理任何错误时如何防止我的应用崩溃?

powershell - Powershell 函数中的错误处理

javascript - jQuery post - 等待响应

c# - 关于 ASP.Net 中的弹出窗口

javascript - 如何为文本字段生成动态名称和 ID

javascript - 使用 Prototype 时如何防止 Ajax 调用发回服务器?