javascript:如何中止 $.post()

问题描述 投票:0回答:3

我的post方法如下图:

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

  });
})

我尝试在单击新按钮时中止旧帖子: 所以我累了

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

但是这不起作用。所以我想知道如何解决这个问题?

javascript jquery html ajax
3个回答
11
投票

您必须在

gettopic
事件之外定义变量
click

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

1
投票
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()

-1
投票

根据服务器和客户端的带宽和延迟,发布请求可能会在不到 20 毫秒的时间内发生。 Windows 默认双击时间为 500 毫秒,所以不,您不能也不应该期望能够中止它。

© www.soinside.com 2019 - 2024. All rights reserved.