This demo helps you understand the collaboration between JS and servers.
The document structure is as follows: main. js table.html validateUserName. jsp (for the code, see the end of the article)
The page is displayed as follows:
After selecting the first input box, a defined prompt is displayed on the right. As follows:
Enter "olduser". In order to simplify the verification process, verify whether the username is "olduser" by hard encoding in validateUserName. jsp and return a JSON string. If yes, {valid: false} is returned; otherwise, {valid: true} is returned}
Process:
After the user enters "olduser" and removes the focus from the current input box, the onchange event is triggered and the main. the usernameOnChange function in js. This function sends a verification request to the server, which is sent by validateUserName. jsp processes this request. ValidateUserName. jsp judges "olduser" as an existing user name, and returns {valid: false} to the browser. After the browser receives the server's response, the usernameValidationHandler function in main. js processes the response. If it judges that the valid is false, it displays the defined error message.
If valid is true, the error message is not displayed.
The problem solved is that when valid is set to false, the error message is not displayed on the page and should be dijit. byId ("tableuserName "). displayMessage (errorMessage); this sentence does not take effect. This problem cannot be solved for the time being. You will learn how to find a solution later.
Table.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
Main. js
function usernameOnChange() {console.log("run");var userName = dijit.byId("tableuserName").getValue();if(userName == ""){console.log("user name is empty");return;}dojo.xhrGet({url:"validateUserName.jsp?userName=" + userName,handleAs:"json",handle:usernameValidationHandler});}function usernameValidationHandler(response){//console.log("get response");dijit.byId("tableuserName").displayMessage("yes");if(!response.valid){var errorMessage = "user name already exists";//console.log(errorMessage);dijit.byId("tableuserName").displayMessage(errorMessage);}}
ValidateUserName. jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%try{System.out.println("UserName :"+request.getParameter("userName"));if(request.getParameter("userName").equals("olduser")){out.println("{valid:false}");System.out.println("To Brower : false");}else{out.println("{valid: true}");System.out.println("To Brower : true");}}catch(Exception ex){out.println(ex.getMessage());ex.printStackTrace();}%>