10920171018
10920171018
ajax基本它会采用json数据格式的数据传输
1、加载jar文件[struts2-json-plugin-2.5.13.jar],引入jQuery文件
2、编写Action类(接受及响应json数据格式)
1)、接受json的数据(智能解释json数据---->注入到对应的属性)
2)、json数据的拦截解析
3)、json数据的响应(智能将Action属性的对象解释成一条json数据格式)
true
text/html
package com.tiger.action;
import com.opensymphony.xwork2.ActionSupport;
public class JsonAction extends ActionSupport {
/**
* 前台传来的参数
*/
private String id;
private String name;
private String author;
private String type;
@Override
public String execute() throws Exception {
/**
* 根据返回的type数据来判断需要显示的内容
*/
if (getType().equals("literature")) {
setId("001");
setName("莎士比亚");
setAuthor("威廉·莎士比亚");
}else if(getType().equals("it")){
setId("002");
setName("C++入门");
setAuthor("哈哈");
}else if (getType().equals("music")) {
setId("003");
setName("古典乐谱全集");
setAuthor("林俊杰");
}
System.out.println("type = " + getType());
return SUCCESS;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-json-tags"%>
---测试接收JSON格式的数据---
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/json2.js"></script>
<script type="text/javascript">
function struts2_ajax() {
$.ajax("${pageContext.request.contextPath}/jsonaction", {
dataType : "json", // 预期服务器返回的数据类型。
type : "post", // 请求方式 POST或GET
contentType : "application/json", // 发送信息至服务器时的内容编码类型
// 发送到服务器的数据,取得下拉框id返回服务器
data : JSON.stringify({
'type' : $("#books").val()
}),
async : true, // 默认设置下,所有请求均为异步请求。如果设置为false,则发送同步请求
success : function(data) {// 请求成功后的回调函数
console.log(data);
$("#id").html(data['id']);
$("#name").html(data['name']);
$("#author").html(data['author']);
},
error : function() {
alert("数据发送失败");// 请求出错时调用的函数
}
});
}
</script>
选择
it
文学
音乐
编号:
书名:
作者:
true
text/html