如何重复ajax调用直到成功

时间:2013-12-14 12:29:11

标签: jquery

单击“getproduct”按钮时,如果产品不可用,则ajax调用将获取产品或404代码。

我希望每5秒再次调用函数getMyJson,直到返回产品。

有什么想法吗?

$(function () {
    $("#getproduct").click(function getMyJson() {
        $.ajax({
            type: "GET",
            url: "Product/GetProduct",
            dataType: "json",
            success: function (data) {
                //alert("succes");
                $("#name").html(data.Name);
                $("#price").html(data.Price);
            },
            error: function () {
                //alert("fail");
                //callback getMyJson here in 5 seconds
            }
        });
    });
});

1 个答案:

答案 0 :(得分:16)

您可以在setTimeout回调函数

中使用error
$(function () {
    function getMyJson() {
        $.ajax({
            type: "GET",
            url: "Product/GetProduct",
            dataType: "json",
            success: function (data) {
                //alert("succes");
                $("#name").html(data.Name);
                $("#price").html(data.Price);
            },
            error: function () {
                //alert("fail");
                //callback getMyJson here in 5 seconds
                setTimeout(function () {
                    getMyJson();
                }, 5000)
            }
        });
    }
    $("#getproduct").click(function () {
        getMyJson();
    });
});