JavaScript - 确认框.| 是?>从MySQL删除数据/否 - 什么都不做

Fáb*_*nes 2 javascript mysql

我对JavaScript没有多少经验.但是我想用JavaScript和MySQL做一件小事.我可以使用一些帮助.

我有一个用PHP搜索的页面,它根据搜索查询给出了结果.对于每个结果,它会添加3个图像,其中一个图像作为您可以查看内容的URL.您可以编辑该内容的其他地方.

第三个你可以删除.为此,我想做点好事.

就像用户点击图像一样,会出现一个确认对话框.在该框中,它会询问您是否确定要删除数据.如果是,它将删除数据.其中ID =

使用PHP在图像中的JavaScript函数内部的onclick操作中打印ID echo.

如果没有,我们将关闭对话框并继续.

Kaz*_*zar 10

好的,让我们假设以下内容(请原谅我重新澄清问题):

你有一些形式的行,有删除链接,你想确认用户真的想要删除它吗?

我们假设以下HTML:

<tr>
   <td>Some Item 1</td>
   <td><a href="?mode=delete&id=1" class="delete-link">Delete</a></td>
</tr>
<tr>
   <td>Some Item 2</td>
   <td><a href="?mode=delete&id=2" class="delete-link">Delete</a></td>
</tr>
<tr>
   <td>Some Item 3</td>
   <td><a href="?mode=delete&id=3" class="delete-link">Delete</a></td>
</tr>
Run Code Online (Sandbox Code Playgroud)

所以我假设同样的PHP脚本可以运行删除,拿起模式参数:

<?php
    if($_GET['mode'] == 'delete') {
       //Check if there is something in $_GET['id'].
       if($_GET['id']) {

          //Prevent SQL injection, just to be safe.
          $query = "DELETE FROM sometable WHERE id='" . mysql_real_escape_string($_GET['id']) . "'";

          mysql_query($query);
       }
    }
Run Code Online (Sandbox Code Playgroud)

我将在JavaScript方面为此提供两个解决方案 - 第一个使用内联,稍微丑陋的解决方案,第二个使用jQuery(http://jquery.com/),以及不引人注目的JavaScript.

好的,所以对于第一个,我会绑定每个链接的onclick事件.

<tr>
   <td>Some Item 3</td>
   <td><a href="?mode=delete&id=3" class="delete-link" onclick="checkDeleteItem();">Delete</a></td>
</tr>
Run Code Online (Sandbox Code Playgroud)

然后创建一个JavaScript函数:

//This will get called when the link is clicked.
function checkDeleteItem() {
   //show the confirmation box
   return confirm('Are you sure you want to delete this?');
}
Run Code Online (Sandbox Code Playgroud)

正如我所说,我不喜欢这种解决方案,因为它非常突兀,也不是特别强大.

现在,jQuery解决方案:

//Do all this when the DOM is loaded
$(function() {
   //get all delete links (Note the class I gave them in the HTML)
   $("a.delete-link").click(function() {
       //Basically, if confirm is true (OK button is pressed), then
       //the click event is permitted to continue, and the link will
       //be followed - however, if the cancel is pressed, the click event will be stopped here.
       return confirm("Are you sure you want to delete this?");
   });
});
Run Code Online (Sandbox Code Playgroud)

我衷心推荐这个解决方案,因为它更优雅,更好,通常是最好的做法.