reg.html
javascript
<!DOCTYPE HTML> <html> <head> <title> ajax </title> <meta charset="utf-8"/> <script type="text/javascript"> var httpAjax = new XMLHttpRequest(); function checkUser(uname){ if(uname == ""){ return false; } httpAjax.onreadystatechange = function(){ if(httpAjax.readyState == 4 && httpAjax.status == 200){ var res = httpAjax.responseText; res = eval("("+res+")"); var sp = document.getElementById("sp"); if(res.status == 1){ sp.innerHTML = "<font color='red'>"+res.info+"</font>"; var _html =""; for(var i in res['data']){ _html += "<p>"+res['data'][i]+"</p>" } var myobject = document.getElementById('mydiv'); myobject.innerHTML = _html; }else{ sp.innerHTML = "<font color='green'>"+res.info+"</font>"; } } } httpAjax.open("post","user.php",true); httpAjax.setRequestHeader("content-TYPE","application/x-www-form-urlencoded"); var data = "uname="+uname; //user.php?uname="1"&pwd="123","uname=" 是參數,+是鏈接參數鏈接變量的用的,uname是js中的一個不帶$的變量,也就是值 httpAjax.send(data); } </script> </head> <body> <input type="text" id="username" class="username" name="username" onchange="checkUser(this.value)"/><span id="sp"></span> <div id ="mydiv" style="width:200px;height:200px;border:1px red solid"> </div> </body> </html>
user.phpphp
<?php header("content-type:text/html;charset=utf-8"); $pdo = new PDO("mysql:host=localhost;dbname=tk106","root",""); $pdo->exec("set names utf8"); $uname = $_REQUEST["uname"];//post傳值,這裏要改成REQUEST $sql = "select * from stu_info where sname='".$uname."'"; $data = $pdo->query($sql)->fetch(PDO::FETCH_ASSOC); if($data){ $list['status']=1; $list['info']="已經註冊"; $list['data']=$data; echo json_encode($list); }else{ $list['status']=0; $list['info']="未註冊"; $list['data']==""; echo json_encode($list); } ?>