我如何编写一个javascript警告框来提出是或否问题并与php调用集成? [英] how do i write a javascript alert box to give a yes or no question and integrate with php calls?

查看:46
本文介绍了我如何编写一个javascript警告框来提出是或否问题并与php调用集成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何创建一个javascript警告框,询问用户是否要删除记录(他们的查看),当用户按下是时,通过php调用查询来删除数据库行。如果用户按下则不会发生任何事情。

i am trying to figure out how to create a javascript alert box asking the user if they would like to delete a record (that their viewing) and when the user presses yes a query is called through php to delete a database row. and if the user presses no nothing will happend.

想知道如何做到这一点

谢谢

ps:

这就是我所做的,它没有用。

this is what i did and it didnt work.

<script type="text/javascript">
if(window.confirm("Are you sure you want to delete that record?")) { 
<?php
mysql_query("delete from tbl_payments where id = '$id'") or die(mysql_error());
header("Location: dashboard.php");
?>
}
</script>


推荐答案

if (window.confirm("Are you sure?")) {
  // call php code here, either through going to a new page,
  // or by doing an ajax request
}

对于您的更新:问题是PHP代码正在由服务器,它不运行Javascript,而Javascript在客户端运行,不知道PHP代码。

For your update: The problem is that the PHP code is being executed by the server, which does not run the Javascript, and the Javascript runs at the client side, with no knowledge of the PHP code.

这意味着PHP代码将始终运行,只是忽略window.prompt调用,因为它不是PHP的一部分。客户端执行的Javascript看起来像这样:

This means the PHP code will always run, simply ignoring the the window.prompt call, as that is not part of PHP. The Javascript that is executed by the client looks simply like this:

<script type="text/javascript">
if(window.confirm("Are you sure you want to delete that record?")) { 
}
</script>

如果您要访问此页面,这显然无效,因为您要将用户发送给使用Location标题的新页面。

Which obviously does nothing, if you were to even reach this page, because you are sending the user to a new page using the Location header.

您需要做的是将您编写的PHP代码放在第二页上,并将客户端带到该页面,只需执行一次window.confirm()已经运行了。这样的事情:

What you need to do is put the PHP code you wrote on a second page, and take the client to that page, only once the window.confirm() has run. Something like this:

file1.php

<script type="text/javascript">
if(window.confirm("Are you sure you want to delete that record?")) {
  document.location = "file2.php?id=<?php echo $_GET['id'] ?>";
}
</script>

file2.php

<?php
$id = $_GET['id'];
if (!is_numeric($id)) $id = -1;
mysql_query("delete from tbl_payments where id = '$id'") or die(mysql_error());
header("Location: dashboard.php");
?>

这篇关于我如何编写一个javascript警告框来提出是或否问题并与php调用集成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆