简体   繁体   中英

why alert don't work when we use php header function ? .i know window.location.href is solution

why alert function don't work in the following snippet?

<?php
ob_start();
echo "<script>alert('Some text');</script>";
header("location:somepage.php");
?>

It is redirecting the user but not showing the alert . I know window.location.href is the solution but i want the reason why this alert is not working.

thanks in advance

Because the browser will execute the redirect before waiting for DOM to load completely. Your page will tell the browser to redirect and the body of the page contain javaScript that will issue an alert after the DOM completed successfully.

And as standard practice, when using Header redirect you must exit the PHP and don't output anything before setting any header attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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