即使confirm()方法为false,Jquery AJAX也会提交表单

时间:2016-01-30 21:57:22

标签: javascript ajax confirm

<div class="report" data-id="55"></div>

<script>
$('.report').click(function() {
    var id = $(this).data("id");
    confirm("do you really want to report this post?");

    $.ajax({
        url: 'forumreport.php',
        type: 'GET',
        data: 'id='+id,
        success: function(){
            alert("reported!!");
        },
    });
})
</script>

如果用户点击确认表单上的取消,我想停止$.ajax()方法。但是ajax仍然将id发送到.php页面。我该怎么办?

2 个答案:

答案 0 :(得分:0)

confirm method返回一个布尔值,指示提示是否已确认,因此您只需将结果布尔值保存在变量中,并在执行AJAX请求之前检查它是否为真。

$('.report').click(function() {
    var id = $(this).data("id");
    var confirmed = confirm("do you really want to report this post?");

    if (confirmed) {
      $.ajax({
          url: 'forumreport.php',
          type: 'GET',
          data: 'id='+id,
          success: function(){
              alert("reported!!");
          },
      });
    }
});

答案 1 :(得分:0)

Confirm函数返回一个布尔值,指示是否选择了“确定”或“取消”(true表示正常)
https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm

检查confirm函数返回的结果:

<script>
$('.report').click(function() {
    var id = $(this).data("id");
    if(confirm("do you really want to report this post?")){
       $.ajax({
           url: 'forumreport.php',
           type: 'GET',
           data: 'id='+id,
           success: function(){
            alert("reported!!");
           },
       });
    };

})
</script>