我希望用户在登录时,用户名和密码验证正确则显示正确,否则弹出提示框“error”,验证的程序是用ajax连接到intosql2.php后台实现的。代码如下:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
  <script language="javascript">
  function showhint()
  {   var str1=document.form.user.value;
      var str2=document.form.pw.value;
  var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  if (str1.length<1)
  {   alert ("no user");
  return false;}
  if (str2.length<1)
  {
  alert ("no password");
  return false;
  }
  xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4&&xmlhttp.status==200)
  {  document.getElementById("txt").innerHTML=xmlhttp.responseText;}   
  }
  xmlhttp.open("GET","intosql2.php?q="+str1+"&w="+str2,true);//alert("intosql2.php?q="+str1+"&w="+str2);
  xmlhttp.send();
  }
  </script>
</head>
<body><span id="txt">
<form name="form" method="post" >
<table width="200" border="0">
      <tr>
        <td width="117">用户名:
            <input type="text" name="user" maxlength="20" size="15">        </td>
        <td width="46" rowspan="2">
          <input name="button" type="button" onclick="showhint()" style="font-size:24px;height:50px;width:70px" value="登陆">        </td>
      </tr>
      <tr>
        <td>密码:
            <input type="password" name="pw" maxlength="20" size="15">        </td>
        </tr>
      <tr>
        <td colspan="2"><a href="pw_out.php">忘记密码?</a>  <a href="register.php">注册新用户</a></td>
        </tr>
    </table>
</form></span>
</body>
</html>
intosql2.php<?php
header("content-type:text/html; charset=gb2312");
$con = mysql_connect("localhost","root","");
if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }mysql_select_db("clint", $con);
  $sql=mysql_query("select * from clint where name='$_GET[q]'");
$row=mysql_fetch_array($sql);
if ($row[password]==$_GET["w"])
  {
  echo "<font size=2 color=green>login ok!</font>";
  }
  else
  {
echo "<script>alert ('error');</script>";此处不能弹出提示框
  }
  mysql_close($con);
  function gbkToUtf8 ($value) {
return iconv("gb2312", "UTF-8", $value);
}
?>

解决方案 »

  1.   

    这个intosql2.php是ajax后台验证程序,前台只能获得它的返回值,字符串形式的,不能把返回的script代码解析执行,所以前台只能根据返回值来弹出对话框。echo "<script>alert ('error');</script>";  改成 echo '0' ;
    { document.getElementById("txt").innerHTML=xmlhttp.responseText;}   
    这个改成:
    {
     if(xmlhttp.responseText == '0'){alert("出错!");}
     document.getElementById("txt").innerHTML=xmlhttp.responseText;
    }   
      

  2.   


    记得以前有种方法可以在ajax返回js并执行,不过我忘了,但不知alert可否应用,alert执行机制有点不同
      

  3.   

    是这么个样子的,不过改为if(xmlhttp.responseText == '0'){alert("出错!");}else
    { document.getElementById("txt").innerHTML=xmlhttp.responseText;}更好似的。
    谢谢了。