Jquery version of Struts2-Ajax integration

<Pure JavaScript version http://www.cnblogs.com/hzb462606/p/8934787.html >

Most of them are consistent with the JavaScript version, that is, <script> uses jQuery:

 

1. The role of Ajax: it can interact with the background server in an asynchronous way without reloading the page

2. Struts2-Json jar package (including Alibaba's own jar package)

commons-beanutils-1.7.0.jar

commons-collections-3.2.1.jar

commons-httpclient-3.1.jar

commons-jexl-2.1.1.jar

ezmorph-1.0.3.jar

fastjson-1.1.40.jar

gson-2.3.1.jar

json-lib-2.4-jdk15.jar

struts2-json-plugin-2.2.3.jar

2. Build your own Struts2 environment and web.xml configuration file filter

3. Front-end page

<body> 
<label>用户名</label>

<input type="text" id="username"><br>
<label>密码</label>
<input type="password" id="password">
<br>
<input type="button" name="btn_click" value="提交" onclick="axaj_function()"/>
<br />
<label>验证用户是不是root用户:</label>
<label style="color: red;" id="check_content">...</label>
</body>

<script>

//jQuery code
$(document).ready(function(){
$('#btn_click').click(function(){
var name=document.getElementById("username").value;
var password2=document.getElementById( "password").value;
//If you need to upload multiple data, you need to encapsulate it into a json-like object
var mytest={'username':name,'password':password2};

//jQuery-Ajax code
$.ajax({
type:"get", //Upload method
url:"usertest.action", //url address
async:true, //Interaction method: true is asynchronous, false is synchronous
data :mytest, //data source
//task executed when the server response is ready to be processed
//xmlhttp.readyState==4 && xmlhttp.status==200
success:function(data){
//return The string is parsed into a Json object
var json = eval('(' + data + ')');
//{"backpassword":"r","backusername":"person"}
//json.backusername=person
document.getElementById("check_content").innerHTML=json.backusername;
},
//Task executed when server response fails
error:function(data){
window.location.href="index.html";
}


}) ;
});

});
</script>

 

Precautions:

 Ajax method syntax:

 $.ajax( {name:value, name:value, ... })

 This parameter specifies one or more name/value pairs for the AJAX request.

 The possible names/values ​​are listed in the table below:

名称 值/描述
async 布尔值,表示请求是否异步处理。默认是 true。
beforeSend(xhr) 发送请求前运行的函数。
cache 布尔值,表示浏览器是否缓存被请求页面。默认是 true。
complete(xhr,status) 请求完成时运行的函数(在请求成功或失败之后均调用,即在 success 和 error 函数之后)。
contentType 发送数据到服务器时所使用的内容类型。默认是:"application/x-www-form-urlencoded"。
context 为所有 AJAX 相关的回调函数规定 "this" 值。
data 规定要发送到服务器的数据。
dataFilter(data,type) 用于处理 XMLHttpRequest 原始响应数据的函数。
dataType 预期的服务器响应的数据类型。
error(xhr,status,error) 如果请求失败要运行的函数。
global 布尔值,规定是否为请求触发全局 AJAX 事件处理程序。默认是 true。
ifModified 布尔值,规定是否仅在最后一次请求以来响应发生改变时才请求成功。默认是 false。
jsonp 在一个 jsonp 中重写回调函数的字符串。
jsonpCallback 在一个 jsonp 中规定回调函数的名称。
password 规定在 HTTP 访问认证请求中使用的密码。
processData 布尔值,规定通过请求发送的数据是否转换为查询字符串。默认是 true。
scriptCharset 规定请求的字符集。
success(result,status,xhr) 当请求成功时运行的函数。
timeout 设置本地的请求超时时间(以毫秒计)。
traditional 布尔值,规定是否使用参数序列化的传统样式。
type 规定请求的类型(GET 或 POST)。
url 规定发送请求的 URL。默认是当前页面。
username 规定在 HTTP 访问认证请求中使用的用户名。
xhr 用于创建 XMLHttpRequest 对象的函数。

 

4. struts.xml configuration

<package name="default" extends="json-default">
<!-- Here is the action we want to declare the configuration -->
<action name="usertest" class="Action.Test" method="ajax_send">
<!-- type="stream" Sends an InputSream object to the browser, usually used to handle file downloads, and can be used to return AJAX data. -->
<result name="success" type="stream"> 
<param name="contentType">text/html</param> 
<!-- name="input" This attribute can be written freely, inputStream is Action class The field name is also the name of the data variable to be returned, and the name must be the same -->
<param name="input">inputStream</param> 
</result> 
</action>
</package>

 

 

5. Configure Action class

package Action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import com.opensymphony.xwork2.ActionSupport;

import com.alibaba.fastjson.JSONObject;

public class Test extends ActionSupport{
private String username; //接收Ajax传过来的属性名
private String password; //接收Ajax传过来的属性名
private InputStream inputStream; //返回的数据源

public InputStream getInputStream() {
return inputStream;
}

public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Test() {};
public String ajax_send() throws Exception{
System.out.println(username+"-->"+password);
Map<String,String> map=new HashMap<String,String>();
map.put("backusername", username);
map.put("backpassword", password);
String ReturnData=JSONObject.toJSONString(map); //把Map集合封装成Json形式的字符串
inputStream = new ByteArrayInputStream(ReturnData.getBytes("UTF-8")); //转换成UTF-8,避免中文乱码
return SUCCESS;
}
}

 

Guess you like

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