如何只在打开通知列表时检查AJAX请求?

时间:2019-01-11 作者:Adham Mohamed

我使用的插件中有此脚本“DW Notifications“,我面临的问题是ajax自动检查始终在前端工作的新通知,这使得我的站点加载过多。

那么,如何仅在通知列表打开时检查ajax?

我是WordPress的新手,我花了更多的时间来解决这个问题,但我失败了。

jQuery(document).ready(function($){
    var tempPopup;
    var time = dwnotif.dwnotif_current_time;
    var old_time = time;

    if(!$(\'#dw-notifications\').length){
        return;
    }

    var change_numer = 0;
    var minTimeRequest = 2000;
    var maxTimeRequest = 30000;
    var currentTimeRequest = 10000;
    var timeoutPopup = 15000;


    autoCheck();

    function changeTimeRequest(changed = false){

        if(changed){
            currentTimeRequest = currentTimeRequest/2;
        }else{
            change_numer++;
            if(change_numer<5){
                return false;
            }
            currentTimeRequest = currentTimeRequest*2;
            change_numer = 0;
        }

        if(currentTimeRequest<minTimeRequest){
            currentTimeRequest = minTimeRequest;
        }

        if(currentTimeRequest>maxTimeRequest){
            currentTimeRequest = maxTimeRequest;
        }
    }



    function autoCheck(changed = false){
        changeTimeRequest(changed);
        changeTimeItem(time);
        changeReadItem();
        setTimeout(checkNotifications, currentTimeRequest);
    }

    function checkNotifications(){
        $.ajax({
            url: dwnotif.dwnotif_ajax_url,
            type: \'POST\',
            dataType: \'json\',
            data: {
                action: \'dwnotif_check_notifications\',
                nonce: dwnotif.dwnotif_nonce,
                time: time,
            },
            success: function( data ) {

                var changed = false;
                if (data.success) {
                    if(data.result.newest_notifications){
                        $(\'#dw-notifications .list-notification\').prepend(data.result.newest_notifications);

                        if(data.result.count_unchecked){
                            $(\'#dw-notifications\').find(\'.dw-notification-btn\').addClass(\'has-notification\');
                            $(\'#dw-notifications\').find(\'.notif-count-unchecked\').text(data.result.count_unchecked);
                        }

                        if(data.result.newest_notifications_popup){
                            addPopup(data.result.newest_notifications_popup);
                        }

                        changed = true;
                    }

                    /*if(data.result.length>0){
                        for(var i=0;i<data.result.length;i++){
                            $(\'.dw-notifications._\' + data.result[i].id).find(\'.list-notification\').html(data.result[i].html);
                            if(data.result[i].new){
                                addPopup(data.result[i].id, data.result[i].new);
                                changed = true;
                            }
                            if(data.result[i].count_unchecked){
                                addHasNotifications(data.result[i].id, data.result[i].count_unchecked);
                            }
                        }
                    }*/
                    time = data.time;
                }
                autoCheck(changed);
            },
            error: function (request, status, error) {
                autoCheck(false);
            }
        });
    }

    function changeTimeItem(){
        $(\'.dw-notifications .list-notification\').find(\'li\').each(function(e){
            var diff= dw_human_time_diff($(this).data(\'time\'), time);
            $(this).find(\'.notif-time\').text(diff);
        });
    }

    function changeReadItem(){
        //change read all
        var markReadAll = getCookie(\'dw_read_all_time\');
        if(markReadAll){
            // all read
            $(\'#dw-notifications .list-notification\').find(\'.unread\').each(function(){
                var item_time = $(this).data(\'time\');
                if(item_time <= markReadAll){
                    $(this).removeClass(\'unread\').addClass(\'read\');
                }
            });
        }

        //change read item
        var readList = getCookie(\'dw_read_list\');
        if(readList){
            var listItems = readList.split(",");
            for(var i = 0; i < listItems.length; i++){
                $(\'#dw-notifications .list-notification\').find(\'#dw-notif-\' + listItems[i] + \'.unread\').removeClass(\'unread\').addClass(\'read\');
            }
        }

        //change has notification
        var checkedTime = getCookie(\'dw_checked_time\');
        if(checkedTime && checkedTime >= old_time){
            $(\'#dw-notifications .dw-notification-btn\').removeClass(\'has-notification\');
        }
        old_time = time;
    }

    function addPopup(itemHtml){
        var popup_id = \'#dw-notif-popup\';
        if($(popup_id).length){

            $(popup_id).addClass(\'open\');

            var item = $(itemHtml);
            //close popup notify
            item.on(\'click\', function(){
                $(this).closest(\'.dw-notif-popup\').remove();
            });
            $(popup_id +\' ul\').append(item);

            clearTimeout(tempPopup);
            tempPopup = setTimeout( function(){ $(popup_id).removeClass(\'open\'); $(popup_id +\' ul\').html(\'\');}, timeoutPopup);
        }

    }

    //user checked
    $(\'.dw-notification-btn\').on(\'click\', function(){

        $(this).removeClass(\'has-notification\');

        var notifications = $(this).closest(\'.dw-notifications\');

        if(notifications.hasClass(\'open\')){
            notifications.removeClass(\'open\');
        }else{
            notifications.addClass(\'open\');

            if(!dwnotif.dwnotif_is_user_logged_in){
                //if user not logged => return false
                return false;
            }

            $.ajax({
                url: dwnotif.dwnotif_ajax_url,
                type: \'POST\',
                dataType: \'json\',
                data: {
                    action: \'dwnotif_mark_user_checked\',
                    nonce: dwnotif.dwnotif_nonce,
                },
                success: function( data ) {
                    // if (data.success) {
                    //  //read all
                    //  notifications.find(\'.unread\').addClass(\'read\').removeClass(\'unread\');
                    // }
                },
                error: function (request, status, error) {

                }
            });
        }

    });

    //mark item read
    $(document).on(\'click\', \'.list-notification .unread\', function (e) {
        $(this).removeClass(\'unread\').addClass(\'read\');
    }); 

    //mark all as read
    $(\'.dw-notif-mark-all-read\').on(\'click\', function(){
        var notifications = $(this).closest(\'.dw-notifications\');
        var id = notifications.data(\'id\');

        $.ajax({
            url: dwnotif.dwnotif_ajax_url,
            type: \'POST\',
            dataType: \'json\',
            data: {
                action: \'dwnotif_mark_all_as_read\',
                nonce: dwnotif.dwnotif_nonce,
                id: id,
            },
            success: function( data ) {
                if (data.success) {
                    //read all
                    notifications.find(\'.unread\').addClass(\'read\').removeClass(\'unread\');
                }
            },
            error: function (request, status, error) {

            }
        });
    });

    $(document).on(\'click\', function (e) {
        $(\'.dw-notifications\').removeClass(\'open\');
    });
    $(document).on(\'click\', \'.dw-notifications\', function (e) {
      e.stopPropagation();
    });
});

//custom time diff
function dw_human_time_diff( from = false, to = false) {
    if ( !from || !to ) {
        return false;
    }
    var  constants =dwnotif.dwnotif_constants;

    var diff = parseInt(Math.abs( to - from ));

    if ( diff < constants.HOUR_IN_SECONDS ) {
        var mins = Math.round( diff / constants.MINUTE_IN_SECONDS );
        if ( mins <= 1 )
            mins = 1;
        /* translators: Time difference between two dates, in minutes (min=minute). 1: Number of minutes */
        var since = mins==1? mins +\' min\' : mins +\' mins\';
    }  else if ( diff < constants.DAY_IN_SECONDS && diff >= constants.HOUR_IN_SECONDS ) {
        var hours = Math.round( diff / constants.HOUR_IN_SECONDS );
        if ( hours <= 1 )
            hours = 1;
        /* translators: Time difference between two dates, in hours. 1: Number of hours */
        var since = hours==1? hours +\' hour\' : hours +\' hours\';
    }  else if ( diff < constants.WEEK_IN_SECONDS && diff >= constants.DAY_IN_SECONDS ) {
        var days = Math.round( diff / constants.DAY_IN_SECONDS );
        if ( days <= 1 )
            days = 1;
        /* translators: Time difference between two dates, in days. 1: Number of days */
        var since = days==1? days +\' day\' : days +\' days\';
    }  else if ( diff < constants.MONTH_IN_SECONDS && diff >= constants.WEEK_IN_SECONDS ) {
        var weeks = Math.round( diff / constants.WEEK_IN_SECONDS );
        if ( weeks <= 1 )
            weeks = 1;
        /* translators: Time difference between two dates, in weeks. 1: Number of weeks */
        var since = weeks==1? weeks +\' week\' : weeks +\' weeks\';
    }  else if ( diff < constants.YEAR_IN_SECONDS && diff >= constants.MONTH_IN_SECONDS ) {
        var months = Math.round( diff / constants.MONTH_IN_SECONDS );
        if ( months <= 1 )
            months = 1;
        /* translators: Time difference between two dates, in months. 1: Number of months */
        var since = months==1? months +\' month\' : months +\' months\';
    }  else if ( diff >= constants.YEAR_IN_SECONDS ) {
        var years = Math.round( diff / constants.YEAR_IN_SECONDS );
        if ( years <= 1 )
            years = 1;
        /* translators: Time difference between two dates, in years. 1: Number of years */
        var since = years==1? years +\' year\' : years +\' years\';
    }
    return since;
}


function setCookie(cname, cvalue, extimes) {
    var d = new Date();
    d.setTime(d.getTime() + (extimes*1000)); // extimes second
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(\';\');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == \' \') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

1 个回复
最合适的回答,由SO网友:mrben522 整理而成

将呼叫替换为autocheck() 使用以下内容。

$(\'#ID-of-button\').on(\'click\', checkNotifications());
当然你必须更换ID-of-button 带有通知栏切换按钮的ID。这将在单击、打开或关闭按钮时运行ajax调用。

相关推荐

Select2 AJAX和WP查询返回全部,不筛选

所以我在这里有点困惑。我经常使用Select2/AJAX/WP\\u查询来搜索和检索默认的WP帖子类型和我自己的自定义帖子类型。在过去几年中,我构建的几乎每个站点都至少包含一个实现。但是,我目前正在一个网站上搜索自定义帖子类型的结果,它只是返回所有内容。没有发生过滤。这是一个计划工具,管理员正在为一年中的每个月制定一个计划(自定义帖子类型)。时间表的标题为“月-年”,即。\'January 2022\'.问题是,如果您搜索“一月”,例如,您将得到返回的每个存在的时间表。包括2022年2月、2021 6月等