Javascript: how to abort $ .post ()

I have a 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 interrupt the old recording when I pressed a new button: So I'm tired

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

However, this does not work. So I thought, how can this be fixed?

+4
source share
3 answers

You must define your variable gettopicoutside the event.click

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

A post request, depending on server and client bandwidth and latency, can occur in less than 20 ms. The default double-click time is 500 ms by default, so no, you cannot and should not expect to be able to interrupt it.

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

jquery, :

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()
0

Source: https://habr.com/ru/post/1651369/


All Articles