如何调用AJAX只有一次AJAX

2023-09-11 01:03:09 作者:戳你痛处了i

我称这个code函数:

I call function from this code :

    <div id="header-button-news" class="header-button-info">
        <a href="javascript:;" title="Новости" onclick="showNews()"></a>
        <div class="new">2</div>
    </div>

我的功能

function showNews()
{          
        //other js which show block 

        jQuery("#loader").show();


        //ajax which load content to block
        jQuery.ajax({
            type: "GET",
            url: link,
            dataType: "html",
            success: function(data) {
                jQuery('#top-info-news').html(data);   
            },
            complete: function(){
                jQuery('#loader').hide();
            },
        });
}

我怎样才能让只有一次的AJAX调用?因此,当内容加载和页面不refresed不加载AJAX?我试图做布尔变量,但没有,我suppouse那是因为我每次打电话的功能。请给我一个想法,怎么做。

How can I make only once ajax call? so when content is loaded and page was not refresed not to load ajax? I tried to do boolean variables but nothing, I suppouse it is because I call everytime function. Please give me an idea how to do.

谢谢

推荐答案

当你想要做的事该事件。

When you want to do something on that event.

确定,当你已经加载数据。

Identify when you have already loaded your data.

var loaded = false;

function showNews() {
    //other js which show block 

    jQuery("#loader").show();


    if(loaded) return;

    //ajax which load content to block
    jQuery.ajax({
        type: "GET",
        url: link,
        dataType: "html",
        success: function(data) {
            jQuery('#top-info-news').html(data);   
        },
        complete: function(){
            jQuery('#loader').hide();
        },
    });

    loaded = true;
}

或者使用之一。当你要调用它一次。

Or use one. when you want to call it once.

<a href="javascript:;" title="Новости" onclick="showNews()" class="showNews"></a>

jQuery('.showNews').one('click', function() {
    // your code
});

附加处理程序的事件为元素的处理程序最多一次每个单元的执行。

参考