AJAX+PHP驗證用戶名重複

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

相關文章
相關標籤/搜索