Struts2 ajax submission form (using jquery plug-in)
1 index. jsp
<% @ Page language = "java" contentType = "text/html; charset = UTF-8"
PageEncoding = "UTF-8" %>
<Script type = "text/javascript" src = "JS/jquery-1.9.1.min.js"> </script>
<Script type = "text/javascript">
$ (Document). ready (function (){
$ ("# Btn_login"). click (function (){
Var url = 'ajaxlogin ';
// Obtain the form value and save it to params as json data
Var params = {
LoginName: $ ("# username"). val (),
Password: $ ("# password"). val (),
};
// Use the $. post Method
$. Post (
Url, // the url to be accepted by the server
Params, // parameters passed
Function qwer (data) {// The function parameter data executed after the server returns is the data sent from the server to the client.
Alert (data); // The value corresponding to root. Here is result !!
Var member = eval ("(" + data + ")"); // parse the package data to json format
Certificate ('{result'}.html ("Welcome:" + member. name + "" + "your password:" + member. password );
},
'Json' // data transmission type json
);
});
});
</Script>
User name:
Password:
Ajax information is displayed here:
2 action class
Package org. action;
Import com. opensymphony. xwork2.ActionSupport;
Import java. util. HashMap;
Import java. util. Map;
Import net. sf. json. JSONObject;
Public class AjaxLoginAction extends ActionSupport {
// User Ajax returns data
Private String result;
// Struts property-driven mode. The attribute of the page is automatically filled here.
Private String username;
Public String getUsername (){
Return username;
}
Public void setUsername (String username ){
This. username = username;
}
Private String password;
Public String getResult (){
Return result;
}
Public void setResult (String result ){
This. result = result;
}
Public String getPassword (){
Return password;
}
Public void setPassword (String password ){
This. password = password;
}
@ Override
Public String execute (){
// Use a Map as an Example
Map Map = new HashMap ();
// Add a data record for the map and upload the loginName on the page
Map. put ("name", this. username );
Map. put ("password", this. password );
// Json processing of the map object to be returned
JSONObject jo = JSONObject. fromObject (map );
// Call the toString method of the json object to convert it to a string and assign it to result
This. result = jo. toString ();
// Test the result
System. out. println (this. result );
Return SUCCESS;
}
}
3 struts. xml
Result
4. jar packages
5. jquery. js
6 run: