1. 程式人生 > >php處理ajax

php處理ajax

.class request 通過 action get check parse ready inf

首先安裝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