为什么如果失败,我无法保留调用 api

Why I cannot keep call api if fail?

本文关键字:保留 调用 api 如果 失败 为什么      更新时间:2023-09-26

下面如果我的代码...

$(document).ready(function() {
    var counter=0;
    $.ajax({
        url: "http://www.test.com:1234/testService",
        method: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: data
    })
    .done(function(data) {
        console.log(data);
    })
    .fail(function(errMsg) {
        console.log(errMsg);
        counter++;
        console.log(counter);
        if(counter <=3){
            $.ajax(this);
        }
        else {
            alert("Three times failed");
        }
    });
});

运行此代码将从 API 获取正确的数据。

但是,如果我删除 api url 末尾的"e",API 将失败,我想要的是重试直到失败三次并发出一些消息警报。

但是此代码不起作用。

我该怎么办?

您可以做的是创建一个函数,该函数发出 ajax 请求并在失败时再次调用该函数。

$(document).ready(function () {
    var counter = 0;
    function apiCall() {
        $.ajax({
                url: "http://www.asiavista.com.tw:9595/ccplapi/service.svc/CheckService",
                method: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: JSON.stringify({ClientType: 1})
            })
            .done(function (data) {
                console.log(data);
            })
            .fail(function (errMsg) {
                console.log(errMsg);
                counter++;
                console.log(counter);
                if (counter <= 3) {
                    apiCall(); // Try api call again
                } else {
                    alert("Three times failed");
                }
            });
    }
    apiCall(); // Trigger the first api call
});