无法使用 PHP 显示警告消息

Can not display alert message using PHP

本文关键字:显示 警告 消息 PHP      更新时间:2023-09-26

我在尝试使用 PHP 显示警报消息时遇到一个问题。我在下面解释我的代码。

<?php
if($id){
      $message = "Added successfully.";
      echo "<script type='text/javascript'>alert('$message');</script>";
      header("location:http://localhost/crm_complain/index.php");
  }else{
      $message = "Unable to add.''nTry again.";
     echo "<script type='text/javascript'>alert('$message');</script>";
      header("location:http://localhost/crm_complain/index.php");
  }
?>

在这里,我的问题是警报消息框根本不起作用。我需要在 if/else 条件内警报消息应该有效。请帮助我。

警报消息工作正常,但标头无法正常工作。如果要在收到警报消息后重定向,请尝试以下操作:

die('<script>location.href = "'. $url .'"</script>');

你不能得到这样的警报,因为你使用的是header()。您可以按以下方式解决此问题:

您的 PHP 代码(传递成功状态):

<?php
if($id)
{
    //$message = "Added successfully.";
    header("location:http://localhost/crm_complain/index.php?success=1"); // success status
}
else
{
    //$message = "Unable to add.''nTry again.";
    header("location:http://localhost/crm_complain/index.php?success=0"); // failure status
}
?>

您需要在 index.php 文件中添加以下代码以获取警报:

<script type="text/javascript"> 
    var phpVar = "<?php if(isset($_GET['success'])) {echo $_GET['success'];} else { echo ""; } ?>";
    if(phpVar == 1){
        alert('Added successfully.');
    }
    else if(phpVar == 0){
        alert('Unable to add.''nTry again.');   
    }
    else{
        // nothing
    }
</script>