簡體   English   中英

jQuery-如果瀏覽器標簽集中,則執行AJAX-不起作用

[英]jQuery - If browser tab is focused, then do AJAX - Not working

我有一個確定當前瀏覽器窗口或選項卡是否處於活動狀態的代碼。 如果處於活動狀態,則選項卡的標題為“活動”,否則為“模糊”

一切正常。 這是代碼:

 $(window).on("blur focus", function (e) {
            var prevType = $(this).data("prevType");

            if (prevType != e.type) {   //  reduce double fire issues

                if (e.type == "blur") {
                    document.title = 'blurred';
                } else if (e.type = "focus") {
                  document.title = 'focus';
                }
            }

            $(this).data("prevType", e.type);
        })

上面的代碼工作正常。

現在,如果我向其中添加AJAX,它將無法正常工作。

 $(window).on("blur focus", function (e) {
            var prevType = $(this).data("prevType");

            if (prevType != e.type) {   //  reduce double fire issues

                if (e.type == "blur") {
                    document.title = 'blurred';
                } else if (e.type = "focus") {

                    var interval = function () {
                        $.ajax({
                            url: "<?php echo base_url('home/get') ?>",
                            cache: false,
                            success: function (html) {
                                $("#text").val(html);
                                document.title ='focus';
                            },
                        });
                    };


                    setInterval(interval, <?php echo $int ?>);
                }
            }

            $(this).data("prevType", e.type);
        })

如果聚焦,則說聚焦。 如果我沒有聚焦,它會說“模糊”不到一秒鍾,然后再次聚焦。 我不知道為什么 我想說的不是很模糊,那就是模糊的。 添加AJAX代碼無法使其正常工作。

請幫忙。 謝謝。

您需要在blur事件中使用clearTimeout() 我的代碼不斷輪詢服務器中的數據,但是當我離開頁面時,它將停止輪詢。 請查看下面的實現。 我在這里的應用程序中做了類似的操作:

$(window).blur(function() {
    clearTimeout(getJsonTmr);
    clearTimeout(updatePreviewTmr);
}).focus(StartTimers);

function StartTimers () {
    // Every half a second, 
    getJsonTmr = setInterval(function () {
        $.get("/doodles/update?getJson&DoodleID=" + DoodleOptions.DoodleID, function (data) {
            data = JSON.parse(data);
            if (!DoodleOptions.isActive)
                clearDoodleCanvas();
            $.each(data, function (index) {
                drawFromStream(data[index]);
            });
        });
    }, 500);

    updatePreviewTmr = setInterval(function () {
        $.post("/doodles/update?updatePreview", {
            "DoodleID": DoodleOptions.DoodleID,
            "DoodlePreview": canvas.toDataURL()
        });
    }, 5000);
}
StartTimers();

您可以使用上面的代碼作為參考並進行更改。

一個簡單的參考實現為您...

function timers() {
  tmrAjax = setInterval(function () {
    $.get(/* ... */);
  }, 1000);
}

timers();

$(window).blur(function () {
  clearInterval(tmrAjax);
}).focus(timers);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM