今天在學習SpringBoot時遇到了這麼一個問題,
我想要的目的:通過ajax擷取資料,并通過Model渲染View,實作跳轉頁面并渲染資料。
但是,ajax能過擷取到HTML源代碼,但是無法跳轉頁面。
先來看看我寫的代碼
JS:
function func2(){
$.ajax({
url : "/getData2",
type : "POST",
//dataType : "html",// 傳回類型
data : {}, // 請求的資料 參數
success : function(data){ // 接收從背景傳回的資料
console.log(data);
}
})
}
Controller層
@RequestMapping("/getData2")
public ModelAndView getData2(){
ModelAndView mv = new ModelAndView();
mv.setViewName("main"); // 渲染的頁面 main.html
List list = userService.getData2();
mv.addObject("list",list);
mv.addObject("name","xzy");
return mv;
}
main.html【使用了thymeleaf模闆】
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>main</title>
</head>
<body>
<h2 th:text="${name}"></h2>
<ul>
<li th:each="brand : ${list}" th:text="${brand.brandName}"></li>
</ul>
</body>
</html>
來看看結果:
從控制台 debugger能看出 頁面已經成功渲染了
但是,跟我期望有出入,
我希望的頁面的跳轉。
通過查詢資料,發現ajax隻能實作局部重新整理,無法執行整體的頁面跳轉并攜帶資料。
是以,我才用了以下兩種方案,僅供參考
解決方案
解決方案1
把ajax的使用改為form表單的送出。
<form action="/getData2">
<button type="submit">click FORM</button>
</form>
解決方案2
使用 document.write() 方法重新寫頁面
function func2(){
$.ajax({
url : "/getData2",
type : "POST",
//dataType : "html",// 傳回類型
success : function(data){ // 接收從背景傳回的資料
document.write(data);
}
})
}
// 此方法有局限性,頁面重新整理後頁面會還原。