如何解决Javascript确认,即使取消也可以运行表格?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (41)

有一个删除付款方式的ajax表单处理程序。当用户点击“删除”时,它会显示确认弹出窗口。但是,即使用户点击“取消”,它仍会运行表单并删除付款方式。我需要改变什么?

HTML:

<form class="sg-inline-form" method="post" action="">
  <input type="hidden" name="sg_customer_id" value="customerID">
  <input type="hidden" name="sg_card_id" value="cardID">
  <a href="#" class="delete-card" onclick="return confirm('Are you sure?')">Delete</a>
</form>

AJAX:

$('.delete-card').click(function() {
    $('.ajax-loading').show();
    const $form = $(this).parent();
    const customer = $form.find('input[name=sg_customer_id]').val();
    const card = $form.find('input[name=sg_card_id]').val();
    $.ajax({
        url: sg_obj.ajaxurl,
        data: {
            'action': 'sg_delete_payment_source',
            'customer' : customer,
            'card' : card
        },
        success:function(data) {
            // This outputs the result of the ajax request
          $('.ajax-loading').hide();
          $('#ajax-messages').addClass('alert alert-success').html('The payment source has been deleted. <a href=".">Refresh Page</a>');
        },
        error: function(errorThrown){
          $('.ajax-loading').hide();
          $('#ajax-messages').addClass('alert alert-danger').html('An error occurred.');
        }
    });  
    });
提问于
用户回答回答于

不要使两个单独的onClick绑定。您可以通过更改此类代码来执行您的功能

HTML:

<form class="sg-inline-form" method="post" action="">
  <input type="hidden" name="sg_customer_id" value="customerID">
  <input type="hidden" name="sg_card_id" value="cardID">
  <a href="#" class="delete-card">Delete</a>
</form>

AJAX:

$('.delete-card').click(function() {
    if(confirm('Are you sure?')) {
        $('.ajax-loading').show();
        const $form = $(this).parent();
        const customer = $form.find('input[name=sg_customer_id]').val();
        const card = $form.find('input[name=sg_card_id]').val();
        $.ajax({
            url: sg_obj.ajaxurl,
            data: {
                'action': 'sg_delete_payment_source',
                'customer' : customer,
                'card' : card
            },
            success:function(data) {
                // This outputs the result of the ajax request
              $('.ajax-loading').hide();
              $('#ajax-messages').addClass('alert alert-success').html('The payment source has been deleted. <a href=".">Refresh Page</a>');
            },
            error: function(errorThrown){
              $('.ajax-loading').hide();
              $('#ajax-messages').addClass('alert alert-danger').html('An error occurred.');
            }
        });
    }
});
用户回答回答于

没有条件来测试confirm()实际上说的内容。此链接显示如何获取实际confirm()响应,您应该在提交$.ajax请求之前测试响应是真还是假

扫码关注云+社区

领取腾讯云代金券