这是php代码
<?php
$username=$_POST['q'];
// $password=$_POST['passwotd'];
//$username="a";
//$password="a";

//打开数据库
$con=mysql_connect("localhost:3307","root","admin");
if(!$con){
echo "连接数据库失败".mysql_error();
}
mysql_select_db("my_db",$con);
$select="select * from users where username='".$username."'";
$result=mysql_query($select);
$row=mysql_fetch_array($result);
if(!mysql_num_rows($result)){
echo "没有数据!";
}else{
echo "查询成功";
}
?>这是前台代码:
<body>
<form method="post">
<label>用户名:<input  type="text" id="username"></label>
<label>密码:<input  type="password" id="password"></label>
<input type="submit" value="登录" id="btn" onclick="Login()"/>
</form>
<div id="txtshow"></div>
</body>
<script>
var xmlHttp=null;
function Login(){
var un=document.getElementById("username").value;
if(un==""){
alert("文本框不能为空");
return;
}
xmlHttp=GetHttpObject();
if(xmlHttp==null){
alert("连接http协议失败!");
}
var url="login.php";
// url=url+"?txt="+txt;
// url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=StateChange;
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send("q="+un);
}
function StateChange(){
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("txtshow").innerHTML=xmlHttp.responseText;
// alert(document.getElementById("txtshow").innerHTML=xmlHttp.responseText);
}
}
function GetHttpObject(){
var xmlHttp=null;
try{
xmlHttp=new XMLHttpRequest();
}catch(e){
//TODO handle the exception
try{
xmlHttp=ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
//TODO handle the exception
xmlHttp=ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</script>

解决方案 »

  1.   

    不知道你遇到了什么问题!1、js 代码没有阻断表单的正常提交
    2、$select="select * from users where username='".$username."'"; 中 $username 未定义
      

  2.   

    $username不是接收了post传过来的数据了吗?在第一句写的;
    这个小程序的作用是:
    就是在前端的用户名那输入文本查询后如果有则在表单下面的那个div(id是txtshow)中显示文字说明查到了,反之显示没查到;
    现在我遇到的问题是:
    我提交的时候有时候会返回数据有时候不会返回数据(就是div中有时会有字有时候没有),而且还没有局部刷新
      

  3.   

    好,那就算我第二条没说
    但第一条总还是存在的:如果表单提交的返回,迟于 ajax 提交。则页面被重置,ajax 返回的数据就不复存在了