停止重复的ajax调用

时间:2014-07-18 12:27:55

标签: javascript php jquery ajax

我正在创建一个应用程序,其中包含大量产品,每个产品都有一个按钮。我的计划是用户点击其中一个按钮,我有一个javascript(jquery)函数,它每秒开始使用按钮的id作为参数识别产品,发出ajax请求。

我计划使用的功能是Execute an Ajax request every second

的第二个答案

我们的想法是在用户感兴趣的时候每秒检查产品的状态(可以不断变化)。

当用户再次点击该按钮时,我想停止查看此特定产品的状态,但我无法弄清楚如何执行此操作。在我看来,我想用户可能已经点击了3个按钮,因此每秒发生3个ajax请求,每个都有不同的产品ID。如何停止具有用户点击的产品ID的定期请求停止?

1 个答案:

答案 0 :(得分:0)

我最近做了类似的事情,我每隔几秒钟就有一次间隔运行,当一些事件发生时,我完全停止了这个过程。我假设您正在使用Javascript,所以类似下面的内容。你可以查看" someVar"如果你愿意,在计时器通话中,由你决定...

   var someVar = false, intervalId;
    $(function () {
        // Attach event handler to button
        $('#ButtonId').click(function (e) {
            if (!someVar) {
                e.preventDefault();
                someVar = true;
                //Start interval
                intervalId = setInterval(CheckStatus, 3000);
            } else {
                // Stop the interval!
                clearInterval(intervalId);
                someVar = false;
            }
        });
    });

    function CheckStatus() {
        // I used MVC, but you can use whatever you need to generate the URL
        var checkUrl = '@Url.Action("CheckStatus", "SomeController", new { intervalId = "_intervalId_" })'.replace('_intervalId_', intervalId).replace(/&/g, "&");

        $.ajax({
            url: checkUrl,
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                // do something with the status - data.Status perhaps?
            },
            error: function () {
                //handle error
            }
        });
    }