php處理ajax

首先安裝wamp,若安裝過mysql則終止進程防止衝突,能夠訪問localhost說明成功。在www目錄下新建項目,使用localhost訪問。php

php:css

<?php
    //3.獲取ajax傳過來的內容處理
    header("content-Type:text/text;charset=utf-8");
    
    $username=$_POST['name'];
    if($username=='admin'){
        echo '{"inf":"該用戶名不合法","sta":"0"}';
    }
    else if($username=='richard'){
        echo '{"inf":"該用戶名已被註冊","sta":"1"}';
    }
    else{
        echo '{"inf":"該用戶名能夠註冊","sta":"2"}';
    }
    
?>

 

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            .green{
                color: green;
            }
            .red{
                color: red;
            }
        </style>
        <script>
            window.onload=function(){
            
                function id(id){
                    return document.getElementById(id);
                }

                function ajax(){
                    var oAjax=new XMLHttpRequest();
                    return oAjax;
                }

                id('username').onkeyup=function(){
                
                //1 創建ajax引擎
                    var xhr=ajax();
                //3 php後端操做
                    var url='/m18AjaxT/checkNameJson.php?name='+id('username').value;
                    xhr.open('POST',url,true);
                    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                    var data="name="+id('username').value;
                //2 發送請求,get用null,由於經過url發送
                    xhr.send(data);
                    xhr.onreadystatechange=function(){
                        if(xhr.readyState==4 && xhr.status==200){
                //4 渲染dom        
                            var information=JSON.parse(xhr.responseText).inf;
                            var sta=JSON.parse(xhr.responseText).sta;
                            id('inf').innerHTML=information;
                            if(sta==0){
                                id('inf').className="red";
                            }else if(sta==1){
                                id('inf').className="red";
                            }else{
                                id('inf').className="green";
                            }
                        }
                    }
                }
                
            }
        </script>
        

    </head>
    <body>
    <form action="" method="get">
        username:<input type="text" id="username" />
        <input type="button" name="btn" id="btn" value="驗證" />

    </form>
    
        <span id="inf">this is infomation</span>
    
    </body>
</html>
相關文章
相關標籤/搜索