开发者

ajax repeats previous requests

开发者 https://www.devze.com 2023-04-04 05:58 出处:网络
I\'m working with codeigntier and i\'m trying some stuff with ajax. This is somewhat difficult to explain.

I'm working with codeigntier and i'm trying some stuff with ajax. This is somewhat difficult to explain.

I have a controller Products with a method "overview", and a view "products_overview".

This is the controller

This is the view

My problem is, is when I make the ajax call in the view in this part:

$('body').delegate('#notification-close', 'click', function(){
    $('#notification').fadeOut(200, function(){
        $('#notificati开发者_运维问答on').remove();
    });

    $('#blanket').fadeOut(200).remove();

    $.ajax({
        type: 'GET',
        url: '<?php echo $current_get_url; ?>',
        success : function (result) {
            $('#column-middle').html(result);
        }
    });

});

It doubles the ajax call everytime i use it. And something else. The products controller creates pagination links. When I go back and forth a few times, I also make ajax calls. Let's say I do that 4 times. Then, when I use the above ajax call, it will execute those 4 previous calls and then start doubling from that!

So, i'm kind of lost here. When I put a setTimeout on $('#column-middle').html(result), it will execute once, but then give a jQuery error that "result" is not defined.


You should return false from a delegate handler function to stop event bubbling, e.g.:

$('body').delegate('#notification-close', 'click', function(){
    // processing

    // stop further handlers from executing
    return false;
});

See caveats section here. You can also abuse closure scope properties to prevent call doubling:

var column_middle_working = false;
$('body').delegate('#notification-close', 'click', function(){
    if (column_middle_working) return;
    column_middle_working = true;
    // do what you do

    $.ajax({
        type: 'GET',
        url: '<?php echo $current_get_url; ?>',
        success : function (result) {
            $('#column-middle').html(result);
            column_middle_working = false;
        }
    });

});

But still recommend you finding a real reason of this behavior.


Have you tried adding undelegate('click')?

$('body').undelegate('click').delegate('#notification-close', 'click', function(){
    $('#notification').fadeOut(200, function(){
        $('#notification').remove();
    });

    $('#blanket').fadeOut(200).remove();

    $.ajax({
        type: 'GET',
        url: '<?php echo $current_get_url; ?>',
        success : function (result) {
            $('#column-middle').html(result);
        }
    });

});
0

精彩评论

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