在PhP中运行javascript警报


Run javascript alert within PhP

我一直想发布一个javascript警报(一个带有消息的弹出窗口),简单地说"谢谢!你已经被添加了!"。用户在表单中输入详细信息并单击提交按钮后。

我已经在谷歌上搜索了如何做到这一点,但当添加它时,它从未奏效,并尝试了不同的方法,但现在却被如何做到它所困扰。如果有人知道我做错了什么,那么任何帮助都将不胜感激。

我还想在一个单独的php文件中注意到这一点。

下面你会发现我的代码;

insert.php

<?php
$con=mysqli_connect("localhost","cl51-main-3i6","password","cl51-main-3i6");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql="INSERT INTO emails ( Firstname, Lastname, Email) VALUES ( '$firstname', '$lastname', '$email')";
if (!mysqli_query($con,$sql)) {
    die('Error : ' . mysql_error($con));
}
echo '<script language="javascript">';
echo 'alert("Thank you! You've now joined the e-mail club!")';
echo '</script>';
header("Location: http://isometricstudios.co.uk/news.html");
exit;
mysqli_close($con);
?>

问题是因为header()将立即执行重定向。在<script>中使用window.location而不是header(location)

<?php
$con=mysqli_connect("localhost","cl51-main-3i6","password","cl51-main-3i6");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql="INSERT INTO emails ( Firstname, Lastname, Email) VALUES ( '$firstname', '$lastname', '$email')";
if (!mysqli_query($con,$sql)) {
    die('Error : ' . mysql_error($con));
}
echo '<script language="javascript">';
echo 'alert("Thank you! You've now joined the e-mail club!")';
echo 'window.location.href="http://isometricstudios.co.uk/news.html";';
echo '</script>';
exit;
mysqli_close($con);
?>

现在,只有按下ok按钮时,警报才会显示并重定向。

您是否在字符串中转义了'?

echo 'alert("Thank you! You''ve now joined the e-mail club!")';

您必须转义回显的字符串中的单引号:

echo 'alert("Thank you! You''ve now joined the e-mail club!")';

除了一行之外,您的代码很好

 echo 'alert("Thank you! You've now joined the e-mail club!")';

您使用的是"来引用该行,但您有一个"。改为写"You have"。:)

echo 'alert("Thank you! You have now joined the e-mail club!")';

你也可以像其他回答者所说的那样逃避它,但这让我认为中的代码稍微混乱了一点

如果使用Location Header重定向浏览器,则不会执行页面本身上的任何javascript代码,因为将加载重定向到的页面。

此外,我认为在调用头函数之前,您不能回显或以其他方式输出任何内容。

如果你想显示警报,请在你重定向到的页面上显示,或者,如果这不在你的控制范围内,请使用javascript重定向,而不是使用Location标头:

document.location = 'http://isometricstudios.co.uk/news.html';

此外,在编写javascript时不使用echo可能更容易,因为这样你就必须转义引号,而这在中是失败的

echo 'alert("Thank you! You've now joined the e-mail club!")';

在php标签之外保留javascript更容易,所以类似的东西

<?php
(do server-side php stuff)
?>
<script>
(do client-side javascript stuff)
</script>
<?php
(do more server-side php stuff)
?>