How to use ajax form validation, async form validation with ajax

In traditional web applications, the user is authenticated by providing a form to the server, the server verifies the user information in the form, and then returns the verification result. In such a processing method, the client must wait until the server returns the processing result. Do something else, and refresh the entire page in the process.

In the Ajax processing method, the user's information can be sent to the server asynchronously through the XMLHttpRequest object. After the server completes the processing of the user's identity information, the processing result is returned to the user through the XMLHttpRequest object, in an asynchronous way without refreshing the page. to complete the authentication of the user's identity.

Use Ajax to verify the login data. Suppose the correct user name is "Zhang San" and the correct password is "123456". When the user logs in, judge whether the user name and user password are correct, and if they are correct, jump to the welcome page; otherwise, an error will be prompted on the login page.

form page login.html

please enter user name:

Please enter password:

When the "Login" button is clicked, the fromCheck() function is called to verify the user information asynchronously using ajax.

function fromCheck(){

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

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

var url = "/ajax/check"; //ajax sends a request to check user information there

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

var method = "POST";

sendRequest(url,method,params,callBack);

}

The sendRequest() method in the fromCheck() method is the encapsulation of the asynchronous request sent by ajax. The complete code to encapsulate ajax is as follows:

var xmlHttpRequest = null;

//Create XMLHttpRequest object

function createXHR(){

try{

xmlHttpRequest = new XMLHttpRequest();

}catch(e1){

//Compatible with different versions of IE browsers

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("Cannot create AJAX object");

}

}

/**

* Send client request

* url: the requested address

* method: the method of the request, GET or POST request

* params: parameters passed to the server

* callback: response function

*/

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";//访问欢迎页面

}

}

}

欢迎页面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";

}

}

运行结果

登录成功

31b426cec09d

微信图片_20190712214630.png

31b426cec09d

微信图片_20190712214621.png

登录失败

31b426cec09d

微信图片_20190712214602.png

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324512136&siteId=291194637