1 function ajax() 2 { 3 var xmlHttp=null; 4 if(windows.XMLHttpRequest){ 5 xmlHttp=new XMLHttpRequest(); 6 } 7 else{ 8 if(windows.ActiveXObject){ 9 xml ...
一次比一次更加簡化,提高代碼利用率,
1 function ajax() 2 { 3 var xmlHttp=null; 4 if(windows.XMLHttpRequest){ 5 xmlHttp=new XMLHttpRequest(); 6 } 7 else{ 8 if(windows.ActiveXObject){ 9 xmlHttpReq=new ActiveXObject("Microsoft.XMLHTTP"); 10 } 11 } 12 var handler=null; 13 this.fun=function(url,mode.synchro,_handler){ 14 handler=_handler; 15 xmlHttp.open(mode,url,synchro); 16 xmlHttp.send(null); 17 }; 18 this.callback=function(){ 19 if(xmlHttp.readyState==4){ 20 if(xmlHttp.status==200){ 21 handler(xmlHttp.responseText); 22 }else{ 23 alert("請求失敗"); 24 } 25 } 26 } 27 28 function ajaxPost(url,postStr,onsuccess) 29 { 30 var xmlHttp=window.XMLHttpRequest():new ActiveXObject('Microsoft.XMLHttp'); 31 xmlHttp.open("POST",url,true); 32 xmlHttp.onreadystatechange=function() 33 { 34 if(xmlHttp.readyState==4){ 35 if(xmlHttp.status==200){ 36 onsuccess(xmlHttp.responseText); 37 } 38 else{ 39 alert('Ajax伺服器返回錯誤!'); 40 } 41 42 } 43 } 44 xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 45 xmlHttp.send(postStr); 46 } 47Ajax的封裝
1 <?php 2 //連接資料庫 3 $conn=mysql_connect('127.0.0.1','username','password'); 4 if($conn){ 5 mysql_select_db("test",$conn); 6 mysql_query("set names 'utf-8'"); 7 } 8 else{ 9 die(); 10 }; 11 //用戶驗證 12 $username=$_POST['username']; 13 $password=$_POST['password']; 14 15 $sql="select * from Users where username='$username'"; 16 17 $result=mysql_query($sql) or die("用戶名不存在"); 18 $num=mysql_num_rows($result); 19 if($num){ 20 echo 1; 21 $_SESSION['Z_USERNAME']=$username;//保存登錄用戶 22 }else{ 23 echo 2; 24 mysql_close(); 25 } 26 } 27 ?> 28
1 function loginCheck(){ 2 var username=document.getElementById('username').value; 3 var password=document.getElementById('password').value; 4 var postStr="username="+username+"&password="+password; 5 if(username==""){ 6 alert("用戶名不能為空,請重新輸入"); 7 return false; 8 } 9 else if(password==""){ 10 alert("密碼不能為空,請重新輸入!"); 11 return false; 12 } 13 else{ 14 ajaxPost("login.php",postStr,function(result){ 15 if(result=="1"){ 16 alert('恭喜您,登錄成功!'); 17 } 18 else if(result=="2"){ 19 alert("密碼輸入有誤,請重新輸入!"); 20 } 21 }); 22 } 23 }