天天看點

如何使用ajax表單驗證,使用ajax進行異步表單驗證

在傳統的Web應用中,使用者的身份驗證是通過向伺服器提供表單,伺服器對表單中的使用者資訊進行驗證,然後傳回驗證的結果,在這樣的處理方式中,用戶端必須等到伺服器傳回處理結果才能進行别的操作,而且在這個過程中還會重新整理整個頁面。

在Ajax的處理方式中,可以把使用者的資訊通過XMLHttpRequest對象異步發送給伺服器,在伺服器完成對使用者身份資訊的處理後,把處理結果通過XMLHttpRequest對象傳回使用者,以異步的方式在不重新整理頁面的情況下完成對使用者身份的驗證。

利用Ajax實作對登入資料的驗證。假設正确的使用者名為“張三”,正确的密碼為“123456”。在使用者登入的時候判斷使用者名和使用者密碼是否正确,如果正确則跳轉到歡迎頁面;否則,在登入頁面提示錯誤。

表單頁面login.html

請輸入使用者名:

請輸入密碼:

點選“登入”按鈕時,調用fromCheck()函數使用ajax異步驗證使用者資訊。

function fromCheck(){

var userName = document.getElementById("userName").value;

var userPwd = document.getElementById("userPwd").value;

var url ="/ajax/check"; //ajax向該處發出檢查使用者資訊的請求

var params = "userName="+userName+"&userPwd="+userPwd;

var method = "POST";

sendRequest(url,method,params,callBack);

}

在fromCheck()方法中的sendRequest()方法是對ajax發送異步請求的封裝。封裝ajax的完整代碼如下:

var xmlHttpRequest = null;

//建立XMLHttpRequest對象

function createXHR(){

try{

xmlHttpRequest = new XMLHttpRequest();

}catch(e1){

//相容不同版本的IE浏覽器

var _msXmlHttp = new Array("Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.5.0",

"Msxml2.XMLHTTP.4.0","Msxml2.XMLHTTP.3.0",

"Msxml2.XMLHTTP","Microsoft.XMLHTTP");

for(int i=0;i<_msxmlhttp.length>

try{

xmlHttpRequest = new ActiveXObject(_msXmlHttp[i]);

if(xmlHttpRequest!= null)break;

}catch (e2){}

}

}

if(xmlHttpRequest == null){

alert("不能建立AJAX對象");

}

}

function sendRequest(url,method,params,callback) {

createXHR();

if(!xmlHttpRequest)return false;

xmlHttpRequest.onreadystatechange = callback;

if(method === "GET"){

xmlHttpRequest.open(method,url+"?"+params,true);

xmlHttpRequest.send(null);

}

if(method === "POST"){

xmlHttpRequest.open(method,url,true);

xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

xmlHttpRequest.send(params);

}

}

在sendRequest()方法中method有兩種方式"GET"和"POST",需要注意這兩種方式向伺服器傳遞參數方式的不同。

GET請求時,參數是通過"?"拼接在url後面。

xmlHttpRequest.open(method,url+"?"+params,true);

POST請求的參數是通過send()傳遞的。同時,POST請求還需要指定請求頭的"Content-Type"為"application/x-www-form-urlencoded",否則伺服器無法接受到請求的資料。

xmlHttpRequest.open(method,url,true);

xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

xmlHttpRequest.send(params);

在sendRequest()方法中callback參數為響應函數,該函數為使用者定義的在ajax接受到伺服器的響應後要去幹什麼。在這個例子中,我們希望在接受到"error"的響應資訊時,在登入頁面中

//ajax響應的處理函數

function callBack() {

if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200){

var info = xmlHttpRequest.responseText;

if(info === "error"){

document.getElementById("showMsg").innerText="使用者名或密碼錯誤!";

}else{

//info === "success"

window.location.href="/ajax/welcome" target="_blank" rel="external nofollow" ;//通路歡迎頁面

}

}

}

歡迎頁面welcome.html

Login Success ! Welcome

controller層

伺服器端用Spring Boot寫。

@Controller

@RequestMapping("ajax")

public class AjaxController {

@GetMapping("/login")

public String login(){

return "login";

}

@RequestMapping(value = "/check",method = RequestMethod.POST)

@ResponseBody

public void loginCheck(HttpServletRequest request,HttpServletResponse response)

throws IOException{

response.setContentType("text/html;charset=UTF-8");

request.setCharacterEncoding("UTF-8");

PrintWriter out = response.getWriter();

String userName = request.getParameter("userName");

String userPwd = request.getParameter("userPwd");

if(!"張三".equals(userName) || !"123456".equals(userPwd)){

out.print("error"); // 失敗

}else{

out.print("success"); //成功

}

}

@GetMapping("/welcome")

public String welcomePage(){

return "welcome";

}

}

運作結果

登入成功

如何使用ajax表單驗證,使用ajax進行異步表單驗證

微信圖檔_20190712214630.png

如何使用ajax表單驗證,使用ajax進行異步表單驗證

微信圖檔_20190712214621.png

登入失敗

如何使用ajax表單驗證,使用ajax進行異步表單驗證

微信圖檔_20190712214602.png