点击取消按钮仍然调用ajax

onclick cancel button still calls ajax

本文关键字:调用 ajax 按钮 取消      更新时间:2023-09-26

按钮点击看起来像这个onclick="return confirm('Are you sure to delete this item?')"。即使点击了取消按钮,文章仍然会被删除。

然后在jquery中。

$(document).ready(function(){
    $('.btn').click(function(event){
    event.preventDefault(); 
        $a = $(this).text().trim();
        if ($a == "Delete") 
        {
            var postid = $(this).next('.postid').val();
            $(this).closest(".todo-content").fadeOut('slow');
            $.ajax({
                type: "POST",
                url: BASE_URL+'classes/deletepost',
                dataType: 'json',
                data: {postid: postid},
                async: false,
                success: function( data ) {
              },
              error: function(xhr, status, error) {
                  // check status && error
            }
      });
        }
    });
});

是否有无论如何取消调用ajax,如果取消在确认单击?

为什么不简单地从两个地方的事件转移到一个地方呢?将confirm从HTML中移出并将其放入javascript中,如下所示:

$(document).ready(function(){
    $('.btn').click(function(event){
       if (!confirm('Are you sure to delete this item?'))
         return;
       event.preventDefault(); 
       /* code to delete here */
    });
});

我认为,你可以这样使用

在{event.preventDefault();}之后的Ajax函数这一行添加在

下面如果(

!confirm("Are you sure")) return;

修改你的代码,将confirm包含在javascript中,而不是内联。

$('.btn').click(function(event){
if(!confirm('Are you sure to delete this item?'))
return;
    event.preventDefault(); 
...
...
...

完全删除onclick,并在函数中构建代码:

function deleteItem() {
    if (confirm('Are you sure to delete this item?')) {
        // code to delete...
    }
}
$(document).ready(function(){
    $('.btn').click(function(event){
        deleteItem();
    });
});

是否有方法取消对ajax的调用,如果在点击确认?

是的,这是可能的。您可以将confirm的结果放入变量中:

onclick="doDelete=confirm('Are you sure to delete this item?');"

在jQuery代码中你可以检查变量的值:

$(document).ready(function(){
  $('.btn').click(function(event){
    event.preventDefault();
    if (doDelete) {
      ...
    }
  });
});

然而,可能并不意味着它是最好的解决方案。最明显的解决方案是在jQuery代码中调用confirm