Java後台通過輸出流直接輸出數據(非頁面跳轉),前台頁面如何接收並解析這些數據?
@ResponseBody
@RequestMapping("/api/data")
public void getData(HttpServletResponse response) throws IOException {
// 設置響應類型為JSON
response.setContentType("application/json;charset=UTF-8");
// 構建數據對象
Map<String, Object> result = new HashMap<>();
result.put("status", "success");
result.put("message", "操作成功");
result.put("data", Arrays.asList("項目1", "項目2", "項目3"));
// 序列化為JSON並寫入輸出流
String json = new ObjectMapper().writeValueAsString(result);
response.getWriter().write(json);
}
$.ajax({
url: '/api/data',
type: 'GET',
dataType: 'json',
success: function(response) {
if (response.status === 'success') {
console.log('接收到數據:', response.data);
// 更新頁面UI
renderData(response.data);
}
},
error: function(xhr, status, error) {
console.error('請求失敗:', error);
}
});
| 環節 | 關鍵點 | 說明 |
|---|---|---|
| 後台輸出 | @ResponseBody / response.getWriter() | 直接輸出數據而非視圖解析 |
| 數據格式 | JSON (application/json) | 跨語言、易解析、標準化 |
| 編碼設置 | charset=UTF-8 | 防止中文亂碼 |
| 前台解析 | dataType: 'json' | jQuery自動反序列化為JS對象 |