⚡ AJAX + JSON
+ +1. JSON 结果类型
+使用 struts2-json-plugin 实现 AJAX 返回 JSON
+// struts.xml 配置 +<action name="getUser" class="com.demo.UserAction"> + <result type="json"> + <!-- 可选: 只包含指定属性 --> + <param name="includeProperties">user\..*,success</param> + </result> +</action>+
2. Action 示例
+public class UserAction extends ActionSupport { + + private User user; + private boolean success; + private String message; + + // getter 是必须的,JSON 插件只序列化有 getter 的属性 + public User getUser() { return user; } + public boolean isSuccess() { return success; } + public String getMessage() { return message; } + + public String getData() { + user = new User("张三", "zhangsan@email.com"); + success = true; + message = "获取成功"; + return SUCCESS; + } +}+
3. 前端 AJAX 调用
+// 原生 fetch +fetch('/getUser') + .then(r => r.json()) + .then(data => { + console.log(data.user); + console.log(data.success); + }); + +// jQuery +$.getJSON('/getUser', function(data) { + $('#username').text(data.user.username); +});+
4. 完整示例:实时搜索
+// HTML +<input type="text" id="keyword" onkeyup="search(this.value)"/> +<div id="results"></div> + +// JS +function search(keyword) { + $.getJSON('/search', {keyword: keyword}, function(data) { + $('#results').empty(); + data.results.forEach(function(item) { + $('#results').append('<div>' + item.name + '</div>'); + }); + }); +}+