Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
740 views
in Technique[技术] by (71.8m points)

jquery - How to call ajax only once

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>

My function is

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

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.

thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

"Attach a handler to an event for the elements. The handler is executed at most once per element."

reference


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...