现在的位置: 首页 > 综合 > 正文

怎么利用js判断用户名和密码是否为空,如不空则跳到指定网页。

2013年03月31日 ⁄ 综合 ⁄ 共 1326字 ⁄ 字号 评论关闭

问:代码如下

</style>
<?php
if(isset($_POST['Submit']) && $_POST['Submit']=="登录"){   //通过isset()函数对登录按钮进行判断 
$user=$_POST['Text1'];           //通过$_POST函数调用表单文本域的值
$pass=$_POST['Password1'];          
 if(empty($user)||empty($pass)){        //通过if语句判断用户名或是密码不能为空
  echo "<script>alert('用户名或密码不能为空');
  </script>"; //用户名或是密码为空时,给出提示
 }
}
?>  
</head>
<body>
<div id="container">
 <div id="banner"></div>
 <div id="content">
    <div id="deng">
 <form method="post">
     <table style="width:100%;">
     <tr>
      <td>选择用户:<select name="select">
          <option value="1">管理员</option>  
    <option value="2">其他</option> 
   </select>
   </td>
     </tr>
            <tr>
                <td>
                    用户名:<input id="Text1" type="text" name="Text1"  /></td>
            </tr>
            <tr>
                <td>
                     密  码:<input id="Password1" name="Password1" type="password"  /></td>
            </tr>
            <tr>
                <td>
                 <input type="submit" name="Submit" value="登录"/>
    </td>
            </tr>   
        </table>
 </form>
 
</div>
 </div>

答:把下面的代码添加到 head 中

<script type="text/javascript">
function checkLoginForm() {
    var un = document.getElementById("Text1");
    var pw = document.getElementById("Password1");
    if(un.value == "" || pw.value == "") {
        alert("用户名或密码不能为空");
        return false;
    }
}
</script>

把 <form method="post"> 改为

<form method="post" action="login.php" onsubmit="return checkLoginForm()">

你之前的 form 没有 action,需要有一个网址去 post,根据你的文件名修改 login.php

如果用户名和密码不为空,你不应该让网页跳转,而是直接提交表单。

你可以把现在这个页面命名为 login.php,然后提交给自己,在 PHP 中进行页面跳转

if(empty($user) || empty($pass)) {
     echo "<script>alert('用户名或密码不能为空');</script>";
 }
 else {
     // 这里检查用户名和密码是否匹配
     //、、、
      
     // 跳转到其它页面
     header("Location: index.php");
 }

抱歉!评论已关闭.