最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - javascript: How to abort $.post() - Stack Overflow

programmeradmin5浏览0评论

I have the post method as shown below:

$(".buttons").click(function(){
  var gettopic=$.post("topic.php", {id: topicId}, function(result){
  // codes for handling returned result

  });
})

I tried to abort the old post when a new button is clicked: So I tired

$(".buttons").click(function(){
    if (gettopic) {
        gettopic.abort();
    }
    var gettopic=$.post("topic.php", {id: topicId}, function(result){
         // codes for handling returned result
    });
})

However this is not working. So I wondered how this could be fixed?

I have the post method as shown below:

$(".buttons").click(function(){
  var gettopic=$.post("topic.php", {id: topicId}, function(result){
  // codes for handling returned result

  });
})

I tried to abort the old post when a new button is clicked: So I tired

$(".buttons").click(function(){
    if (gettopic) {
        gettopic.abort();
    }
    var gettopic=$.post("topic.php", {id: topicId}, function(result){
         // codes for handling returned result
    });
})

However this is not working. So I wondered how this could be fixed?

Share Improve this question edited Aug 16, 2016 at 11:42 Arunjith R S 8621 gold badge14 silver badges23 bronze badges asked Aug 16, 2016 at 6:58 badbyebadbye 3092 silver badges13 bronze badges 1
  • Possible duplicate of abort AJAX post – David Makogon Commented Aug 17, 2016 at 15:47
Add a ment  | 

4 Answers 4

Reset to default 11

You have to define your variable gettopic outside the click event

var gettopic;
$(".buttons").click(function(){
    if (gettopic)
    {
    gettopic.abort();
    }
    gettopic=$.post("topic.php", {id: topicId}, function(result){
               // codes for handling returned result
    });
})
var xhr = [];

$('.methods a').click(function(){
    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;
});

Using jquery you can use in this way:

var xhr = $.ajax({
    type: "POST",
    url: "some.php",
    data: "name=John&location=Boston",
    success: function(msg){
        alert( "Data Saved: " + msg );
    }
});

//kill the request
xhr.abort()

Just use this code

$.post.abort();

A post request, depending on server and client bandwidth&latency, can happen in less than 20ms. Windows default double-click time is 500 ms, so no, you can't and shouldn't expect to be able to abort it.

发布评论

评论列表(0)

  1. 暂无评论