我正在尝试从thymleaf页面发出Ajax请求。我见过this。
这是我的html页面:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Document</title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"></link>
<script>
function sendURL() {
var url = '/updatePing';
console.log("URI sent :)")
$("#resultsBlock").load(url);
}
</script>
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Ping setup</div>
<div class="panel-body">
<form class="form-horizontal" th:object="${ping}" th:method="post" th:action="@{/updatePing}">
bla
bla
bla
<button id="submit-button" type="submit" class="btn btn-default" onclick="sendURL()">Submit</button>
</form>
</div>
</div>
<div id="resultsBlock">
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
我希望在按下按钮后调用js函数(sendURL()
),然后将params发送到我的控制器。这部分也在运作
但来自控制器的答案并未放在<div id="resultsBlock">
这是我的控制器:
@RequestMapping(value="/updatePing", method=RequestMethod.POST)
public String updatePing(@ModelAttribute PingDTO pingDTO) throws Exception{
PingRequestValidation pv=new PingRequestValidation();
if(pv.checkPingRequestValidation(pingDTO.getUrl())){
return "fragments/success";
}
else
return "fragments/failure";
}
问题是,控制器准确呈现成功和失败页面,
同时我希望这些片段显示在主页中的resultsBlock
标签中。
那么我该如何解决这个问题?
答案 0 :(得分:0)
要使用ajax提交整个表单,请删除onclick
on按钮并使用jQuery创建提交处理程序
$(function(){
$('#formId').on('submit', function(event){
event.preventDefault();// stop browser submitting from
var data = $(this).serialize();
$.post('/updatePing', data , function(response){
$("#resultsBlock").html(response);
}).fail(function(){
alert('Something went wrong')
});
});
});