首页 > 代码库 > php处理ajax

php处理ajax

首先安装wamp,若安装过mysql则终止进程防止冲突,可以访问localhost说明成功。在www目录下新建项目,使用localhost访问。

php:

<?php
    //3.获取ajax传过来的内容处理
    header("content-Type:text/text;charset=utf-8");
    
    $username=$_POST[‘name‘];
    if($username==‘admin‘){
        echo ‘{"inf":"该用户名不合法","sta":"0"}‘;
    }
    else if($username==‘malin‘){
        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>

 

php处理ajax