开发者

Only one AJAX request at a time?

I would like to make sure there is only one AJAX request going on (开发者_运维百科for a user) at a time. This is what I tried:

var ajaxFinished = 1;

$('#selector').keyup(function() {

    if (ajaxFinished == 1) {

        ajaxFinished = 0;

        $.get('test.php', { par : "par" }, function(data) {

            // do stuff with data
            ajaxFinished = 1;

        });
    }

});

But the problem is the AJAX request gets executed only once now even though I activate the event multiple times.


I think Corey has it nailed. Another possibility: Could it be that the code block you quote is inside another function we don't see? Then it could be that ajaxFinished is out of scope - correct me if I'm wrong, my knowledge of JS scoping and anonymous functions is not perfect. In that case, you would have to remove the "var" or declare it in the body.


Could it be that when you $.get an error is occurring and ajaxFinished is never being reset to 1?

You may want to use $.ajax rather than $.get. $.ajax will let you catch success and error events.


I guess ajaxFinished should be a global variable. Remove the var keyword. Try:

ajaxFinished = 1;


if i were coding that function i would split it up and call a timeout

var autocomplete_timeout;

$('#selector').keyup(function() {

    if(autocomplete)
       clearTimeout(autocomplete_timeout);
    autocomplete_timeout = setTimeout(300, "autocomplete('"+ this.val() +"');");
});

function autocomplete(param1, param2){
        $.get('test.php', { par : "par" }, function(data) {

            // do stuff with data
            ajaxFinished = 1;

        });
}

Something along those lines to buffer the ajax call until 300ms after the user has stopped typing

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜