使用 html 和 javascript 允许是否调用表单操作不起作用(在 php 中回应)

Using html and javascript to allow whether a form action gets called or not is not working (echoed in php)

我最初在 PHP / HTML 中编写了一些代码,当单击按钮时,表单操作会将用户带到名为 PHP 的页面 delete.php .

现在我想在 javascript 中添加一个功能,询问用户是否确定他们想要在单击按钮后完成该操作,但我不确定如何不让如果用户选择取消,PHP 表单提交表单操作。

这是代码:

    #delete buttons    previous code: <form action='delete.php' method='post'>
    echo "<form onsubmit='return setAction(this)' method='post'>";
    echo "<td> <button onclick='askConfirm()' type='submit' name='deleteItem' value='" . $line['productCode'] . "' />Delete</button></td>";
    echo "</form>";

    # end table row and loop
    echo "</tr>";
    
    # javascript
    echo '<script type="text/javascript">

    function setAction(){

      if (confirm("Are you sure you want to delete this?") == true) {
        form.action = "delete.php";

      } 
      else {
        return false;
      }
    }

    </script>';

解决方法其实很简单。如果取消确认对话框,此 onsubmit 属性将阻止表单提交。

<form action="delete.php" onsubmit="return confirm('Do you really want to submit the form?');" method="post">
    <input type="submit" name="submit">
</form>