abort AJAX post

前端 未结 1 1165
北恋
北恋 2020-12-21 21:15

My setup is like this (simplified for clarity) :


                      
相关标签:
1条回答
  • 2020-12-21 21:47

    Your xhr variable is local inside the function called when the click event happens.

    When you call the abort method, xhr is not the variable used for the post method.

    The xhr variable needs to be external to the function binded to the click event, otherwise it will be undefined when you check it for other click events.

    Additionally, since you probably need more than one xhr variable to store different post, you should create an array or an object to store the different post.

    var xhr = [];
    
    $('.methods a').click(function(){
        // do something global to the anchors, eg : change the bg color, etc
        // set the target container
        var target = $(this).attr('href');
    
        //if user clicks fb_method buttons
        if($(this).hasClass('fb_method')){
            //do ajax request (add the post handle to the xhr array)
            xhr.push( $.post("/ajax/get_fb_albums.php", function(msg) {                           
                $(target).html('').append(msg).fadeIn();
            }) );
        }else{
            //abort ALL ajax request
            for ( var x = 0; x < xhr.length; x++ )
            {
                xhr[x].abort();
            }
            $(target).fadeIn();
        }
        return false;
    });
    
    0 讨论(0)
提交回复
热议问题