我正在尝试更新数据库中的特定字段,即从电话模型中“分配”的字段。 我尝试在 javascript 中创建一个函数 (setBooleanForCurrentPhone()),它会在 select 的 onchange 中将 id="assignPhone"的值从“true”更改为“false”。
问题是“分配”在数据库中没有改变,因为我还没有提交任何东西。
此外,我尝试制作一个按钮,只是为了测试它,它会调用 setBooleanForCurrentPhone() 函数 onclick,但问题是 这是提交数据,页面跳转到另一个页面,我没有使用最后一个调用 setBooleanForPhone() 的提交按钮。
基本上,我想找到一种在不刷新/更改页面的情况下从数据库更新该值的方法。
<tr>
<td>Employee id:</td>
<td><input type = "text" th:field="*{id}" readonly="readonly" ></td>
</tr>
<tr>
<td>Employee last name:</td>
<td><input type = "text" th:field="*{lastName}" ></td>
</tr>
<tr>
<td>Employee first name:</td>
<td><input type = "text" th:field="*{firstName}" ></td>
</tr>
<tr>
<td>Phone:</td>
<td style="display: none"><input type="text" id="destination" th:field="*{phone}"></td>
<td style="display: none"><input type="text" id="assignPhone" th:field="*{phone.assigned}"></td>
<td>
<select id="source" onchange="copyTextValue(), setBooleanForCurrentPhone()" th:field="${possiblePhones}" >
<option th:value="${employee.phone?.id}" th:text="${employee.phone != null ? employee.phone.brand +' '+ employee.phone.model : 'no phone'}">select phone</option>
<option th:each="possiblePhone : ${possiblePhones}" th:value="${possiblePhone.id}" th:text="${possiblePhone.brand +' '+ possiblePhone.model} "></option>
</select>
</td>
</tr>
<!--submit button-->
<tr>
<td colspan="2">
<button onclick="setBooleanForPhone()" type="submit">Save</button>
</td>
</tr>
</table>
我在互联网上找到了一些东西,但我很确定我做的不对:
function setBooleanForCurrentPhone() {
var n = 'false';
var http = new XMLHttpRequest();
http.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("assignPhone").innerHTML = this.responseText;
}
};
http.open("POST","employee/edit/{id}",true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(n);
}
最佳答案
您可以使用 Ajax 来实现这一点。 Ajax 代表异步 JavaScript 和 XML。它将允许您在不刷新页面的情况下提交表单。如果您使用的是 jQuery,那么您可以使用 $ajax
来实现,如果您使用的是 JavaScript,则可以使用 XMLhttprequest
来实现。
关于javascript - 如何在不刷新/提交页面的情况下发送 POST 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57555074/