简体   繁体   English

在PHP中调用javaScript警报后,无法重新加载页面

[英]Reloading a page won't work after calling a javaScript alert in PHP

I have a contact-us page in my site. 我的网站上有一个“ contact-us页面。 When user submits a form it will go to mailIt.php and do the necessary to send that mail. 当用户提交表单时,它将转到mailIt.php并进行必要的发送。 After sending that it will refresh the code. 发送后,它将刷新代码。

Since I wanted to add notification kinda thing to notify the user that the mail has been sent, I changed the code to display a javaScript alert in the page. 由于我想添加通知类,以便通知用户邮件已发送,因此我更改了代码以在页面中显示javaScript警报。 But after that alert will be shown and the page loading will stop and it will remain in the mailIt.php page (with inout text). 但是之后,将显示该警报,并且页面加载将停止 ,并将保留在mailIt.php页面中(带有inout文本)。

@mail($email_to, $email_subject, $email_message, $headers);
?>
    <script type="text/javascript">
        alert("Thank you for contacting us!");
    </script>
<?php
echo("in");
header('Location: /contact_us.html');   
echo("out");

The only part I added is the, 我添加的唯一部分是

?>
    <script type="text/javascript">
        alert("Thank you for contacting us. We will be in touch with you very soon !");
    </script>
<?php

Why is this happening ? 为什么会这样呢? How can I prevent that ? 我该如何预防呢?

Remember that header() must be called before any actual output is sent http://php.net/manual/en/function.header.php 请记住,必须先调用header(),然后才能发送任何实际输出http://php.net/manual/en/function.header.php

You are sending the javascript pop up before you call the header() function. 您正在发送JavaScript弹出窗口,然后再调用header()函数。

A solution would be to print the javascript popup and then load the contents of ./contact_us.html and print that to your page, like so: 一种解决方案是打印javascript弹出窗口,然后加载./contact_us.html的内容并将其打印到您的页面,如下所示:

echo '<script type="text/javascript">
alert("Thank you for contacting us!");
</script>';

$html = file_get_contents('./contact_us.html');
echo $html;

And if you want to be sure the mail has been sent, you should put the mail() function in a if() statement. 并且,如果要确保已发送邮件,则应将mail()函数放在if()语句中。 mail() returns a bool: true if succeeded and false if failed. mail()返回一个布尔值:如果成功,则返回true;如果失败,则返回false。

if(mail($email_to, $email_subject, $email_message, $headers)){
    echo '<script type="text/javascript">
    alert("Thank you for contacting us!");
    </script>';

    $html = file_get_contents('./contact_us.html');
    echo $html;
}
else{
    echo 'Oops, something went wrong!';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM