javascript - 防止单击按钮时出现多个排队的 POST

标签 javascript jquery html ajax

例如,当用户单击一个按钮时,服务器会发送一个 div,然后将其附加到正文中,但是没有逻辑阻止用户将 POST 排队直到没有完成。

这会导致一个问题,即它忽略了只有一个 div 可能存在的逻辑,一旦排队的 POST 完成就立即附加多个。

我怎样才能避免这个问题?

从服务器发送的 Div :

'<div id="test_div"></div>'

按钮事件:

$('body').on('click', '#test_button', function(){
    $.post('get_test_div/',function(response){
        //The following if is ignored if there are uncompleted queued POSTs
        if($('#test_div').length < 1){
            $('body').append(response);
        }
    })
}) 

最佳答案

一种替代方法是在单击按钮时将其禁用。如果需要,您可以再次启用它:

$('body').on('click', '#test_button', function(){

    $('#test_button').prop('disabled', true);

    $.post('get_test_div/',function(response){
        //The following if is ignored if there are uncompleted queued POSTs
        if($('#test_div').length < 1){
            $('body').append(response);
        }

        // re-enables the button
        $('#test_button').prop('disabled', false);
    })
}) 

关于javascript - 防止单击按钮时出现多个排队的 POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41967027/

相关文章:

javascript - jquery 检查 json var 是否存在

javascript - jQuery 当指向链接时应显示默认隐藏的 div

javascript - 如何选择由 ruby​​ 实例变量表示的动态 ID?

javascript - 从最近的表格行中查找 textarea 的值

html - 使用 html-css 使元素居中

javascript - 通过 JavaScript 按类更改值属性

javascript - 执行后删除自身的 javascript/jquery 函数

php - 在 XAMPP 中使用 CONSTANT 路径时无法看到图像

javascript - 节流、多个客户端请求、Node js 中的 Express 线程

$.each 的 jQuery 替代品