首先是html: 復制代碼 代碼如下: html head meta http-equiv="Content-Type" content="text/html; charset=utf-8" / title 一次簡單的Ajax請求 /title script language="javascript" src="js/ajaxTest.js" /script /head body 用戶名: input id="userName" type="text" /input 密碼: input id="passWord" type="password" /input span id="showInputError" /span br input type="button" value="登錄" /body /html
然后是js: 復制代碼 代碼如下: /** * 普通Ajax的完整訪問過程 */ var xmlHttp
function showSelect()//登錄按鈕點擊后執行這個方法 { var userName=document.getElementById("userName").value; var passWord=document.getElementById("passWord").value; if (userName.length==0)//驗證輸入用戶名是否為空 { document.getElementById("showInputError").innerHTML="用戶名不能為空";//提示用戶名不能為空 return } xmlHttp=GetXmlHttpObject() if (xmlHttp==null) { alert ("Browser does not support HTTP Request") return } var url="ajaxTest.php"http://設置要提交action到后臺的那個處理請求的文件名 url=url+"?userName="+userName+"&passWord="+passWord//為這個路徑加上參數用戶名和密碼 url=url+"&sid="+Math.random()//為這個路徑加上一個隨機數 xmlHttp.onreadystatechange=stateChanged//每當 readyState 改變時,就會觸發 onreadystatechange 事件,readyState 屬性存有 XMLHttpRequest 的狀態信息 xmlHttp.open("GET",url,true)//定義請求的參數 xmlHttp.send(null)//發送請求 }
function stateChanged() { if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")// //0: 請求未初始化 //1: 服務器連接已建立 //2: 請求已接收 //3: 請求處理中 //4: 請求已完成,且響應已就緒 { var a= xmlHttp.responseText;//把相應數據賦值給a if(a=="yes"){ self.location='Main.php';//跳轉到Main.php }else{ document.getElementById("showInputError").innerHTML="用戶名或密碼錯誤";//提示用戶名或密碼錯誤 } } } function GetXmlHttpObject() { var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); } catch (e) { // Internet Explorer try { xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }
最后是php: 復制代碼 代碼如下: ?php $userName=$_GET["userName"]; $pwd=$_GET["passWord"]; $con = mysql_connect("localhost","root","123456"); mysql_select_db("my_test", $con); mysql_query("set names utf8"); $sql="SELECT * FROM Userinfo WHERE userName='".$userName."' AND pwd='".$pwd."'"; $result=mysql_query($sql); $select=mysql_num_rows($result); $a="no"; if ($select 0){$a="yes";} echo $a; mysql_close($con); ? 更多編程語言