AJAX实现
使用ServletAPI实现AJAX
- 和Servlet中的操作思路基本一致
jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ajax</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function() {
$('#btn').click(function() {
$.post("ajax.action", function(data) {
$('#message').html(data);
});
});
});
</script>
</head>
<body>
<input type="button" id="btn" value="get data"/>
<h3 id="message"></h3>
</body>
</html>
- action
public class AjaxAction {
public String execute() throws IOException {
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
response.getWriter().print("struts ajax");
return null;
}
}
JSON数据处理
- 使用struts2** **来实现JSON处理
导入相关的jar包
action代码
public class JsonAction { private JSONArray root; //单个对象是JSONObject public String execute() { List<User> list = new ArrayList<User> (); list.add(new User("char", 20)); list.add(new User("eric", 19)); list.add(new User("chenyu", 18)); root = JSONArray.fromObject(list); //root已经是json格式 //对应的结果集type为json,可以直接返回json格式数据 System.out.println("json: " + root.toString()); return Action.SUCCESS; } public JSONArray getRoot() { return root; } public void setRoot(JSONArray root) { this.root = root; } }
- root已经是json格式
- 对应的结果集type为json,可以直接返回json格式数据
配置文件
<struts> <package name="default" extends="json-default"> <!-- 继承json-default --> <action name="json" class="com.eric.action.JsonAction"> <result type="json"> <!-- type是json --> <param name="root">root</param> </result> </action> </package> </struts>
<pacakge>
继承对象是extends="json=deafult"
<result type="json">
直接返回json数据到前台页面
jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>ajax</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> $(function() { $('#btn').click(function() { $.post('json.action', function(data) { var html = ""; for(var i = 0; i < data.length; i++) { html += "<tr><td>" + data[i].name + "</td><td>" + data[i].age + "</td></tr>" } $('#content').html(html); }, 'json'); }); }); </script> </head> <body> <input type="button" id="btn" value="get data"/> <table width="80%" align="center"> <tr> <td>name</td> <td>age </td> </tr> <tbody id="content"> </tbody> </table> </body> </html>
- 也可以直接调用ServletAPI处理json数据的方式