如何重复ajax调用直到成功 [英] How to repeat ajax call until success

查看:54
本文介绍了如何重复ajax调用直到成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单击按钮"getproduct"时,ajax调用将获取该产品或404代码(如果该产品不可用).

When the button "getproduct" is clicked, the ajax call get the product or the 404 code if the product is not avaible.

我希望每5秒钟再次调用一次getMyJson函数,直到返回产品为止.

I want the function getMyJson being call again every 5 seconds until the product is returned.

有什么想法吗?

$(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
            }
        });
    });
});

推荐答案

您可以在error回调函数中使用setTimeout

You can use setTimeout in error callback function

$(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();
    });
});

这篇关于如何重复ajax调用直到成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆