php應用Ajax技術檢測用戶名

1.搭建Ajax開發框架,代碼如下

<script language="javascript">
var http_request = false;
function createRequest(url) {
    //初始化對象併發出XMLHttpRequest請求
    http_request = false;
    if (window.XMLHttpRequest) {                                        //Mozilla等其他瀏覽器
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType("text/xml");
        }
    } else if (window.ActiveXObject) {                              //IE瀏覽器
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
           } catch (e) {}
        }
    }
    if (!http_request) {
        alert("不能創建XMLHTTP實例!");
        return false;
    }
    http_request.onreadystatechange = alertContents;                     //指定響應方法
                                                                                              
    http_request.open("GET", url, true);                                 //發出HTTP請求
    http_request.send(null);
}
function alertContents() {                                               //處理服務器返回的信息
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            alert(http_request.responseText);
        } else {
            alert('您請求的頁面發現錯誤');
        }
    }
}
</script>

2.編寫JavaScript的自定義函數checkname();用於檢測用戶名是否爲空,當用戶名不爲空時,調用createRequest() 方法發送請求檢測用戶名是否存在,代碼如下:

function checkname()
{
    var username = form1.user.value;
    if (username=="")
    {
        window.alert ("請輸入用戶名");       
    }
    else
    {
                                                                             
createRequest('action/checkname.php?username='+username+'&nocache='+new Date().getTime());
    }
}

3.在頁面添加"檢測用戶名超鏈接"

<td width="93" class="ziti2"><a href="#" onclick="checkname()">[檢測用戶名]</a></td>

4.創建checkname.php處理頁面,代碼如下

<?php
header("Content-type= text/html; charset=utf8");
include "../conn/conn.php";
$GB2312string=iconv( 'UTF-8', 'gb2312//IGNORE' , $RequestAjaxString);           //Ajax中先用encodeURIComponent對要提交的中文進行編碼
$username = $_GET[username];
$sql=mysql_query("select * from user where username='".$username."'")or die (mysql_error());
$info=mysql_fetch_array($sql);
if($info)
{
    echo "祝賀您!用戶名[".$username."]沒有被註冊!";
}
else
{
    echo "祝賀您!用戶名[".$username."]沒有被註冊!";
}
?>


初學PHP,在學習實踐中記錄下問題,技巧,代碼有問題或者有其他意見歡迎提出,共同進步~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章