Because of the use of jquery, we need to introduce the JS file of jquery
In the HTML header
<script type= "Text/javascript" src= "./js/jquery.min.js" ></script>
The specific directory location is changed according to your project.
The HTML for the front end is as follows: "To make the code look clearer, I've cleared out all the styles."
<!--login form--><label> user name </label><input id= "username"id= "password" id= " Login-button "> Login </button>
public.js"Asynchronous Commit I write in this file"
$(function () { //When the login button is clicked,submitting a form asynchronously$ (' #login-button '). Click (function () {
Gets the user name and password entered by the uservarUSM = $ (' #username '). Val (); varPSW = $ (' #password '). Val (); if(USM = = "" | | PSW = = "") {alert ("The user name or password cannot be empty!"); } Else { //submitting a form asynchronously$.ajax ({ data: { "username": USM, "password" : PSW}, Type: "POST" ,URL: "/login" , success:function(flag) {//receiving the server's data}, Error:function(flag) {//Error Handling } }); } });});
SPRINGMVC Backend Controller:
@ResponseBody produces = "text/html;charset=utf-8;") username password) { //data is a JSON object, similar to a map, which can be placed into a key-value pair and uploaded to the front-end jsonobject data = new Jsonobject (); System.out.println ("Username:" +username+ "," +password "); Data.put ("state", true); return data.tostring (); }
Note: The Jsonobject class is used here, and the Maven dependency for this class is:
<!--JSON Support--
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
At the same time, you need to add the Spring-servlet.xml
<mvc:annotation-driven/>
Support for JSON
If you have any errors, please comment on my corrections.
Asynchronous submission of forms with SPRINGMVC and jquery Ajax