我正在将Spring MVC用于我的应用程序。我有一个表格,用于从daterangepicker接收开始日期和结束日期。并且我希望在提交表单后显示另一个在查询后有表格的视图到表单下面的“dataDiv”,但不会重新加载页面。 到目前为止我做了什么,结果是当我提交表单时,它重定向到新页面(request-data.jsp),但表格工作正常。
这是我的代码......
JSP
<form action="view-data" method="get" id="ajaxTest">
<div id="reportrange" class="form-control">
<i class="fa fa-calendar"></i>
<span></span>
<b class="caret"></b>
</div>
<input type="hidden" id="startDate" name="startDate" />
<input type="hidden" id="endDate" name="endDate" />
<input type="submit" value="VIEW" id="ajaxBtn" />
</form>
<div id="dataDiv"></div>
Javascript 我使用Ajax加载另一个视图。
$('#ajaxTest').submit(function(event) {
var startDate = $('#reportrange').data('daterangepicker').startDate;
var endDate = $('#reportrange').data('daterangepicker').endDate;
document.getElementById("startDate").value = startDate;
document.getElementById("endDate").value = endDate;
$.ajax({
url : "../request-data",
type : 'GET',
data : data,
success : function(response) {
alert("success");
$('#dataDiv').html( response );
},
error : function() {
alert("error");
}
});
return false;
});
Spring Controller
@RequestMapping(value = "/request-data", method = RequestMethod.GET)
public ModelAndView requestRanking(HttpServletRequest httpRequest, @RequestParam("startDate") Date stDate, @RequestParam("endDate") Date edDate, RedirectAttributes rd) {
ModelAndView mav = new ModelAndView();
/*
*Query for book created between stDate and edDate
*/
rd.addFlashAttribute("bookForms", bookForms);
mav.setViewName("request-data");
return mav;
}
在 request-data.jsp 视图
中
$(document).ready(function() {
$('.footable').footable();
});
<div>
<c:if test="${!empty bookForms}">
<input type="text" class="form-control input-sm m-b-xs" id="filter" placeholder="Search in table" />
<table id="page-size-example" class="footable table table-stripped" data-page-size="" data-filter=#filter data-sorting="true">
<thead>
<tr>
<th data-type="numeric" data-sort-initial="true">#</th>
<th>BOOKNAME</th>
<th>PRICE</th>
<th>CREATED_DATE</th>
</tr>
</thead>
<tbody>
<c:forEach items="${bookForms}" var="bookForm" varStatus="status">
<tr>
<td>${status.count}</td>
<td>${bookForm.name}</td>
<td>${bookForm.price}</td>
<td>${bookForm.createdDate}</td>
</tr>
</c:forEach>
</tbody>
</table>
</c:if>
</div>
还有其他办法吗?请帮帮我。感谢
答案 0 :(得分:0)
我为你找到了一个解决方案how to use spring4 @RestController to return a jsp page?
您应该为方法添加@ResponseBody
注释,或者如果每个方法都使用ajax,则为您的类添加@RestController
。这个注释使您的控制器/方法与ajax异步工作。
一些代码
@RequestMapping(value = "/request-data", method = RequestMethod.GET)
@ResponseBody
public ModelAndView requestRanking(HttpServletRequest httpRequest, @RequestParam("startDate") Date stDate, @RequestParam("endDate") Date edDate, RedirectAttributes rd) {
ModelAndView mav = new ModelAndView();
mav.setViewName("request-data");
//your actions
return mav;
}