代码之家  ›  专栏  ›  技术社区  ›  EvilDr

Cannot.catch()使用Jquery.ajax()时出错。then()

  •  1
  • EvilDr  · 技术社区  · 6 年前

    但是,我不知道怎么做 .catch JQuery.ajax() 功能。读后 here here , here here 还有其他十几个,到目前为止,我得到了同样的控制台错误:

    TypeError:LoadDataFromApi(…).then(…).catch不是函数

    .接住 这东西不适合我。

    // Cache object to save API data for re-use
    var requestCache = {};
    
    // Get API data and save to cache 
    function LoadDataFromApi(apiUrl) {
        if (!requestCache[apiUrl]) {
            var result = $.ajax({
                type: 'GET',
                url: apiUrl,
                dataType: "json",
                statusCode: {
                    500: function (xhr) {
                        var err = JSON.parse(xhr.responseText);
                        console.log('Message:' + err.Message);
                        // throw err.Message; // removed because this was always an "uncaught exception", even if used within try/catch
                    },
                    200: function (xhr) {
                        // Do nothing here - put result into cache regardless of status code
                    }
                }
            });
            requestCache[apiUrl] = result; // save the JSON data into cache
        }
        return requestCache[apiUrl];
    }
    
    // Called by page on load
    function LoadJsonData() {
        LoadDataFromApi('/api/GetFoo?Row=10')
            .then(function (data) {
                RenderChart(data, 'Removed for legibility');
            })
            .catch(function (error) {
                console.log('Promise catch: ' + error);
            });
        LoadDataFromApi('/api/GetFoo?Row=10') // this returns cached data because API has already been hit
            .then(function (data) {
                RenderChart(data, 'Removed for legibility');
            })
            .catch(function (error) {
                console.log('Promise catch: ' + error);
            });
        LoadDataFromApi('/api/GetBar')
            .then(function (data) {
                RenderChart(data, 'Removed for legibility');
            })
            .catch(function (error) {
                console.log('Promise catch: ' + error);
            });
    }
    
    2 回复  |  直到 6 年前
        1
  •  7
  •   MKougiouris    6 年前

    使用 .fail() 如第一个链接所述 here

    取决于你的jQ版本

    弃用注意事项:jqXHR.success()、jqXHR.error()和 jqXHR.complete()回调从jQuery 3.0开始被删除。你可以用 改为jqXHR.done()、jqXHR.fail()和jqXHR.always()

    编辑: 错误回调应该接受3个参数,所以要这样做

    function(jqXHR,textStatus,errorThrown ){}
    
        2
  •  5
  •   SzybkiSasza    6 年前