[英]Replace partial view with ajax response data
我有兩個視圖adminPage.jsp
和studentForm.jsp
。
在adminPage
,我有一個按鈕,允許用戶從中打開學生(使用ajax獲取studentForm)。 用戶可以以這種形式輸入學生數據,然后單擊注冊按鈕以在數據庫中添加學生。
此操作已成功執行,但是我有一個問題。 從studentForm.jsp
調用發布請求(將學生添加到數據庫中的請求),結果也studentForm.jsp
接收。 我想將現有的studentForm
替換為新的studentForm
(在發布請求后收到回復),但結果是,整個頁面都替換為studentForm
。
我應該改變什么?
這是adminPage,在這里我可以獲取請求並在id為-viewContainer的div元素中加載響應:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function onk() {
$.get({
url: "/student/studentForm",
success: function (result) {
$('#viewContainer').html(result);
}
});
}
</script>
</head>
<body>
<h4>Username: ${user.username}</h4>
<h1>heading 1</h1>
<p> paragraph 1</p>
<p> paragraph 2</p>
<input type="button" id="userAddLoader" value="Add Student" onclick="onk();"/>
<div id="viewContainer" style="background-color: red">
<!-- this is container -->
</div>
</body>
</html>
這是studentForm.jsp
:
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('#form1').onsubmit(function (e) {
var form = $('#form1');
$.post({
url: form.attr("action"),
data: form,
success: function (data) {
$('#viewContainer').html(data);
}
}
);
e.preventDefault(); //avoid to execute the actual submit of the form
});
</script>
</head>
<body>
<c:set var="stat" scope="request" value="${status}"/>
<c:if test="${stat == 'success'}">
<script>
alert("Student was successfully added");
</script>
</c:if>
<h6>New Student Registration</h6>
<form:form action="/student/postStudent" method="post" modelAttribute="user" id="form1">
Username: <form:input type="text" path="username" id="username"/>
Password: <form:input type="text" path="password" id="password"/>
<input type="submit" value="Register">
</form:form>
</body>
</html>
我替換了這個:
$('#form1').onsubmit(function (e) {
var form = $('#form1');
$.post({
url: form.attr("action"),
data: form,
success: function (data) {
$('#viewContainer').html(data);
}
}
);
e.preventDefault(); //avoid to execute the actual submit of the form
});
有了這個:
$('#form1').on("submit", function (e) {
var form = $('#form1');
$.post({
url: form.attr("action"),
data: form.serialize(),
success: function (data) {
$('#viewContainer').html(data);
}
}
);
e.preventDefault();
});
問題解決了。
結論 :
onSubmit
在這種情況下不起作用。 可以使用submit
,但是Jquery docs中描述的更新方法是on("submit", function (e) ...
表單應該序列化form.serialize()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.