JavaScript警告窗口重定向到另一个网页

13
    <?php

session_start();

include_once "connect.php";

$fullName = $_POST['fullname'];
$userName = $_POST['username'];
$emailAdd = $_POST['email'];
$passWord = $_POST['password'];
$query =  mysql_query("SELECT * FROM users where USERNAME = '$username' ");
$result = mysql_fetch_array($query);

  if($fullName == "")
  {

?>
    <script>
      alert("Full Name is required!");
      window.location.href = "registeruser.php";
    </script>
<?php
  }

    else
    {
      if ($userName == "")
      {
?>
        <script>
          alert("Invalid username!");
          window.location.href = "registeruser.php";
        </script>
 <?php     
      }

        else
        {
          if($userName == $result['USERNAME'])
          {
?>
            <script>
              alert("Username already exists!");
              window.location.href = "registeruser.php";
            </script>
<?php
          }

            else
            {
              if ($emailAdd == $result['EMAIL']) 
              {
?>
                <script>
                  alert("Email address is required!");
                  window.location.href = "registeruser.php";
                </script>
<?php
              }

                else
                {
                  if ($passWord == "")
                  {
?>
                    <script>
                      alert("Username is required!");
                      window.location.href = "registeruser.php";
                    </script>
 <?php     
                  }

                    else
                    {
                      if($_POST['password']==$_POST['confirmpass'])
                      {
                        mysql_query("INSERT INTO users (FULLNAME, USERNAME, EMAIL, PASSWORD) 
                        VALUES ('$fullName', '$userName', '$emailAdd', '$passWord')" );
                        mysql_close();
?>    
                        <script>
                          alert("Registered Successfully!");
                          window.location.href = "index.php";
                        </script>
<?php
                      }

                        else
                        {
?>
                          <script>
                            alert("Password and Confirm Password do not match");
                            window.location.href = "registeruser.php";
                          </script>
<?php
                        }
                    }
                }
            }
        }
    }   

?>

它能正常工作。但问题是:弹出警告窗口显示在另一个网页而不是当前页面。这没关系,但是将用户引导到没有内容的另一个网页看起来很糟糕。如果您能帮我解决这个问题,并使JavaScript警告窗口仅显示在同一网页上,请告诉我。实际上,我尝试了一些解决方案,例如..

if($fullName == "")
{
  echo '<script>';
  echo 'alert("Full Name is required!")';
  echo 'window.location.href = "registeruser.php"';
  echo '</script>';
}

将完整路径添加到 echo 'window.location.href = "registeruser.php"'; - Narendrasingh Sisodia
4
也许你应该考虑在AJAX请求中进行此操作。顺便说一下,请不要像这样做 mysql_query("SELECT * FROM users where USERNAME = '$username' "),因为这会打开SQL注入的漏洞。 - Markus Zeller
可能是因为您在HTML上方回显了脚本,在每次提交时页面重新加载并执行回显(而不加载HTML)。要在HTML上方显示警报,请将您的PHP代码移至HTML代码下方。 我必须告诉您,这不是一个好的做法,但可以满足您的要求。 此外,现在不要使用MYSQL(它已被弃用),请使用MYSQLi或PDO。 - Pranay Bhardwaj
不确定您想要实现什么。您是想在不清除用户在页面上输入的任何字段的情况下将用户重定向到 registereduser.php 吗? - ImprobabilityCast
显示剩余3条评论
9个回答

1

你好,你是否尝试使用jQuery的ajax功能?

now is your script just return a json object to say if all is ok //reg.php

session_start();
header('Content-type: application/json');

include_once "connect.php";

// result we return to the user
$response = ['error' => false, 'message' => ''];

$fullName = $_POST['fullname'];
$userName = $_POST['username'];
$emailAdd = $_POST['email'];
$passWord = $_POST['password'];
$query =  mysql_query("SELECT * FROM users where USERNAME = '$username' ");
$result = mysql_fetch_array($query);

if($fullName == "") {
    $response['message'] = 'Full Name is required!';
    $response['error'] = true;
} else {
    if ($userName == "") {
        $response['message'] = 'Invalid username!';
        $response['error'] = true; 
    } else {
        if($userName == $result['USERNAME']) {
            $response['message'] = 'Username already exists!';
            $response['error'] = true;
        } else {
            if ($emailAdd == $result['EMAIL'])  {
                $response['message'] = 'Email address is required!';
                $response['error'] = true;
            } else {
                if ($passWord == "") {
                    $response['message'] = 'Username is required!';
                    $response['error'] = true;
                } else {
                    if($_POST['password']==$_POST['confirmpass']) {
                        mysql_query("INSERT INTO users (FULLNAME, USERNAME, EMAIL, PASSWORD)  VALUES ('$fullName', '$userName', '$emailAdd', '$passWord')" );
                        mysql_close();
                        $response['message'] = 'OK';
                        $response['error'] = false;
                    } else {
                        $response['message'] = 'Password and Confirm Password do not match';
                        $response['error'] = true;
                    }
                }
            }
        }
    }
}

die(json_encode($response));

and // registration.php

<form method=POST action="reg.php" id="myForm">
<!--input goes here-->
</form>

<script src="//path to jquery"></script>

<script>

$(document).ready(() => {

    $('#myForm').on('submit', function (e) {
        e.preventDefault();

        $.post('reg.php', $(this).serialize())
            .done((datas) => {


                if(datas.erreur) {
                    alert(datas.message);
                } else {
                    alert('registration succesfully');
                }
            }).fail(() => {
                alert('connect error !!!');
            });
    });

});
</script>


0
你需要像其他人说的那样,将逻辑移到 HTML 的末尾。其次,你需要在要加载的页面上实现这个逻辑,而不是重定向的页面。这是一个两步逻辑。例如:
你需要在当前脚本中实现 window.location。
然后,在你想要用户被重定向的页面的 标签之前:
<?php
if($fullName == "")
{
  echo '<script>';
  echo 'alert("Full Name is required!")';
  echo '</script>';
}
?>
</body>

所以,在页面加载后,它将正确地发出警报。


0

尝试像这样使用它:

if($fullName == "")
{
    echo "<script language='javascript'>alert('Full Name is required!')</script>";
    echo "<script language='javascript'>window.location.replace('page.php?id=".$crmId."'); </script>";
}

0

使用基础URL,然后将您的自定义路径粘贴到您的页面中,例如:

<?php
if($fullName == "")
{
?>
  <script>
   var MyBaseURL = <?php echo BASE_URL_CONSTANT?>
   var customURL = MyBaseURL."/registeruser.php";
   alert("Full Name is required!");
   window.location.href = customURL;
  </script>
<?php
}
?>

你应该避免使用回显脚本,而是使用带有封闭 PHP 标签的常规脚本块。


我认为他所说的是警报出现时显示的页面,而不是警报后重定向到的页面。 - Barmar

0

你应该将警报放在registeruser.php页面上。让PHP脚本执行以下操作:

header("Location: registeruser.php?message=" . urlencode("Invalid username"));

然后,registeruser.php 可以:
<?php
if (isset($_GET['message'])) {
    ?>
    <script>
    alert(<?php echo json_encode($_GET['message']); ?>);
    </script>
    <?php
}

你有没有漏掉什么?isset($_GET['message']) - TarangP
@TarangP 我有这个,你有什么问题? - Barmar
我认为正确的语法是isset($_GET['message'])。 - TarangP
啊,为什么你不直接说我打错字把]落下了呢? - Barmar

0

这个脚本将在同一页上执行,但您必须使用如下的表单

<form method=POST action="">
<!--input goes here-->
</form>



<?php

session_start();

include_once "connect.php";
if(isset($_POST[submit])){
$fullName = $_POST['fullname'];
$userName = $_POST['username'];
$emailAdd = $_POST['email'];
$passWord = $_POST['password'];
$query =  mysql_query("SELECT * FROM users where USERNAME = '$username' ");
$result = mysql_fetch_array($query);

  if($fullName == "")
  {


  echo '    <script>
      alert("Full Name is required!");
      window.location.href = "registeruser.php";
    </script>';

  }

    else
    {
      if ($userName == "")
      {

        echo '   <script>
          alert("Invalid username!");
          window.location.href = "registeruser.php";
        </script>';

      }

        else
        {
          if($userName == $result['USERNAME'])
          {

          echo '  <script>
              alert("Username already exists!");
              window.location.href = "registeruser.php";
            </script>';

          }

            else
            {
              if ($emailAdd == $result['EMAIL']) 
              {

                echo '<script>
                  alert("Email address is required!");
                  window.location.href = "registeruser.php";
                </script>';

              }

                else
                {
                  if ($passWord == "")
                  {

                   echo ' <script>
                      alert("Username is required!");
                      window.location.href = "registeruser.php";
                    </script>';

                  }

                    else
                    {
                      if($_POST['password']==$_POST['confirmpass'])
                      {
                        mysql_query("INSERT INTO users (FULLNAME, USERNAME, EMAIL, PASSWORD) 
                        VALUES ('$fullName', '$userName', '$emailAdd', '$passWord')" );
                        mysql_close();

                      echo '   <script>
                          alert("Registered Successfully!");
                          window.location.href = "index.php";
                        </script>';

                      }

                        else
                        {

                         echo '  <script>
                            alert("Password and Confirm Password do not match");
                            window.location.href = "registeruser.php";
                          </script>';

                        }
                    }
                }
            }
        }
    }   
}
?>

或者你可以像这样使用 registration.php

<?php
 if(isset($_GET[fname]) && $_GET[fname]==1)
    echo ' <script>
          alert("Full Name is required!");
        </script>';
  if(isset($_GET[uname]) && $_GET[uname]==1 )
      echo '   <script>
          alert("Invalid username!");
        </script>';
  if(isset($_GET[uname]) && $_GET[uname]==2 )
    echo '  <script>
              alert("Username already exists!");
            </script>';
  if(isset($_GET[pwrd]) && $_GET[pwrd]==2 )
  echo '  <script>alert("Password and Confirm Password do not match");
                          </script>';
  if(isset($_GET[pwrd]) && $_GET[pwrd]==1 )
     echo '  <script>alert("Password is invalid");
                          </script>';
    if(isset($_GET[mail]) && $_GET[mail]==1 )
      echo '  <script>alert("invalid mailid");
                          </script>';

?>
<form method=POST action="reg.php">
<!--input goes here-->
</form>

reg.php

<?php

session_start();

include_once "connect.php";
if(isset($_POST[submit])){
$fullName = $_POST['fullname'];
$userName = $_POST['username'];
$emailAdd = $_POST['email'];
$passWord = $_POST['password'];
$query =  mysql_query("SELECT * FROM users where USERNAME = '$username' ");
$result = mysql_fetch_array($query);

  if($fullName == "")
  {
              header('Location:registration.php?fname=1');


  }

    else
    {
      if ($userName == "")
      {
                header('Location:registration.php?uname=1');

      }

        else
        {
          if($userName == $result['USERNAME'])
          {

           header('Location:registration.php?uname=2');
          }

            else
            {
              if ($emailAdd == $result['EMAIL']) 
              {
               header('Location:registration.php?mail=1');

              }

                else
                {
                  if ($passWord == "")
                  {

                                header('Location:registration.php?pwrd=1');
                  }

                    else
                    {
                      if($_POST['password']==$_POST['confirmpass'])
                      {
                        mysql_query("INSERT INTO users (FULLNAME, USERNAME, EMAIL, PASSWORD) 
                        VALUES ('$fullName', '$userName', '$emailAdd', '$passWord')" );
                        mysql_close();

                      echo '   <script>
                          alert("Registered Successfully!");
                          window.location.href = "index.php";
                        </script>';

                      }

                        else
                        {

           header('Location:registration.php?pwrd=2');
                        }
                    }
                }
            }
        }
    }   
}
?>

0
也许尝试在session_start()之后渲染一些HTML。 例如。
<html>
<head>
</head>
<body>
<h1>Login Message</h1>
</body>
</html>

这将为消息出现的页面提供支持。 不过,我认为更好的方法是:根本不要退出php,并使用php header()函数在需要时将您带到适当的页面。


0

你的 location href 语法是错误的。应该像这样:

if($fullName == "")
{
  echo '<script>';
  echo 'alert("Full Name is required!")';
  echo 'window.location.href = SITE_URL."registeruser.php"';
  echo '</script>';
}

这里的SITE_URL是您项目的根路径,例如http://localhost/yourproject/


-1

你可以使用这段代码

    <?php

session_start();

include_once "connect.php";

$fullName = $_POST['fullname'];
$userName = $_POST['username'];
$emailAdd = $_POST['email'];
$passWord = $_POST['password'];
$query =  mysql_query("SELECT * FROM users where USERNAME = '$username' ");
$result = mysql_fetch_array($query);

  if($fullName == "")
  {

?>
    <script>
      if(alert("Full Name is required!"))
      {
            window.location.href = "registeruser.php";
        }
    </script>
<?php
  }

    else
    {
      if ($userName == "")
      {
?>
        <script>
          if(alert("Invalid username!"))
          {
            window.location.href = "registeruser.php";
            }
        </script>
 <?php     
      }

        else
        {
          if($userName == $result['USERNAME'])
          {
?>
            <script>
              if(alert("Username already exists!"))
              {
                    window.location.href = "registeruser.php";
                }
            </script>
<?php
          }

            else
            {
              if ($emailAdd == $result['EMAIL']) 
              {
?>
                <script>
                  if(alert("Email address is required!"))
                  {
                        window.location.href = "registeruser.php";
                    }
                </script>
<?php
              }

                else
                {
                  if ($passWord == "")
                  {
?>
                    <script>
                      if(alert("Username is required!"))
                      {
                            window.location.href = "registeruser.php";
                        }
                    </script>
 <?php     
                  }

                    else
                    {
                      if($_POST['password']==$_POST['confirmpass'])
                      {
                        mysql_query("INSERT INTO users (FULLNAME, USERNAME, EMAIL, PASSWORD) 
                        VALUES ('$fullName', '$userName', '$emailAdd', '$passWord')" );
                        mysql_close();
?>    
                        <script>
                          if(alert("Registered Successfully!"))
                          {
                                window.location.href = "index.php";
                            }
                        </script>
<?php
                      }

                        else
                        {
?>
                          <script>
                           if(alert("Password and Confirm Password do not match"))
                            {
                                  window.location.href = "registeruser.php";
                            }
                          </script>
<?php
                        }
                    }
                }
            }
        }
    }   

?>

当用户点击“确定”按钮时,此代码将重定向页面。 在页面重定向之前,会显示警告消息。


请在您的回答中添加更多描述。 - always-a-learner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接