<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<!-- 这是一个简单的ajax-->
<script>
function ajax()
{
var a=null; //a为ajax初始值为null
try
{
a=new XMLHttpRequest();
}
catch(e)
{
try
{
a=new ActiveXobject("Msxml2.XMLHTTP");
}
catch(e)
{
a=new ActiveXobject("Microsoft.XMLHTTP");
}
}
return a;
}
function aa()
{
//alert("123");
a=ajax();
var name=document.getElementsByName("name").value;  //得到name文本框的值
var url="test2.php";   //服务器在test2中处理
var poststr="name="+name;  //这个不理解?
a.open("POST",url,true);
a.setRequestHeader("Content-Type","application/x-www-form-urlencoded" );//这个不理解?
a.send(poststr); //向服务器test2 发送请求
//alert("123");
//alert("用户名已经存在");
a.onreadystatechange=function()  //定义响应处理函数
{

//alert("用户名已经存在");
if(a.readState==4&&a.status==200)
{
//alert("123");

if(name=="")
{
alert("name不能为空");

}
else if(a.responseTest=="1")
   {
document.getElementById("txt1").innerHTML="用户名已经存在";
}
else if(a.responseTest=="0")
{
document.getElementById("txt1").innerHTML="用户名可用"; 
}

// }

// alert("123");

}

//alert("123");
}</script>
</head>
<body>
<form method="post">
<tr><td>name<input type ="text" id ="name" name="name"  /></td>
<input type ="submit" value="判断" align="middle"  onclick="aa();" /></tr>
</form>
<div id="txt1" align="center"></div>
</body>
</html>

解决方案 »

  1.   

    这是test2 mysql
    <?php
    $name=$_POST['name'];
    header('Content-Type:text/html;charest=gb2312');
    $conn=mysql_connect("localhost","root","123456");
    mysql_select_db("test",$conn);
    mysql_query("set names gb2312");
    $sql="select * from user where name='$name'";
    $result =mysql_query($sql);
    $row=mysql_fetch_array($result);
    if($row) echo "1"; else
    echo "0";
    ?>
      

  2.   

    var poststr="name="+name; //这个不理解?
    构造参数串,格式:名=值[&名=值[&名=值...]]a.open("POST",url,true);
    a.setRequestHeader("Content-Type","application/x-www-form-urlencoded" );//这个不理解?
    因为是 POST 方式传递,所以必须有相应的声明。否在服务器端不认识
      

  3.   

    用jquery的ajax简单明了
    $.ajax({
        type:'post',
        url:'',
        data:str,
        error:function(){
          alert('error');
        },
        success:function(data){
        
        }
    });