ajax.js代码:javascript
var xmlHttp;
function S_xmlhttprequest(){
if(window.ActiveObject){//首先判断浏览器是否支持控件的方式
xmlHttp=new ActiveObject('Microsoft.XMLHTTP');
}else if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}
}
function funphp(name){//ajax传输的函数
var f=document.myform.user.value;
S_xmlhttprequest();
xmlHttp.open("GET","for.php?id="+f,true);//打开请求
xmlHttp.onreadystatechange=byphp;//准备就绪执行
xmlHttp.send(null);//进行发送
}
function byphp(){
if(xmlHttp.readyState==1){//请求已创建,准备发送
document.getElementById("php").innerHTML="loading....";
}else if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
var byphp=xmlHttp.responseText;//获取执行结果
document.getElementById("php").innerHTML=byphp;//目标网页内容
}
}
}php
前端页面index.php代码:html
<script language="javascript" src="ajax.js"></script>
<form method="POST" name="myform" action="">
用户名:
<input type="text" name="user" value="" onblur="funphp('pphp')">
<div id="php"></div>
</form>前端
处理页面for.php代码:java
<?php
if($_GET['id']){
sleep(1);//每执行一次,等待一秒
$conn=mysql_connect("localhost","root","root");
mysql_select_db("test",$conn);
//Ajax中先用encodeURIComponent对要提交的中文进行编码
$GB2312string=iconv('utf-8','gb2312//IGNORE',$RequestAjaxString);
mysql_query("set names gbk");
$name=$_GET['id'];
$sql="select * from tb_user where name='$name'";
echo $sql;
$result=mysql_query($sql);
$arr=mysql_fetch_array($result);
header('Content-type:text/html;charset=gb2312');//指定发送数据的编码格式为GB2312
if($arr){
echo "<br><font color='red'>用户已经存在</font>";
}else{
echo "<br><font color='red'>该用户名可使用</font>";
}
}
?>mysql
若是出现"Warning: Cannot modify header information - headers already sent by ...."ajax
能够尝试去掉: header('Content-type:text/html;charset=gb2312');//指定发送数据的编码格式为GB2312
sql