我有如下表格,它需要向我的 java Servlet 发送一个操作来更新数据库。
如何在没有页面重新加载的情况下提交表单?目前action="myServlet"它让我直接进入一个新页面。如果我删除对 myServlet 的操作,则输入不会添加到我的数据库中。
<form name="detailsForm" method="post" action="myServlet"
onsubmit="return submitFormAjax()">
name: <input type="text" name="name" id="name"/> <br/>
<input type="submit" name="add" value="Add" />
</form>
Run Code Online (Sandbox Code Playgroud)
在我的 Java servlet 视图中,request.getParameter将查找名称并继续将其添加到我的数据库中。
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
if (request.getParameter("add") != null) {
try {
Table.insert(name);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我的 JavaScript 部分,我有一个submitFormAjax函数
function submitFormAjax()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
alert(xmlhttp.responseText); // Here is the response
}
var id = document.getElementById("name").innerHTML;
xmlhttp.open("POST","/myServlet",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name=" + name);
}
Run Code Online (Sandbox Code Playgroud)
在这里问了一个类似的问题 Submit form without reloading page
基本上,在调用函数后做“返回假”。这样的事情应该工作:
<form name="detailsForm"
method="post"
action="myServlet"
onsubmit="submitFormAjax();
return false;"
>
Run Code Online (Sandbox Code Playgroud)
更改表单中的代码
onsubmit="submitFormAjax(event)"
Run Code Online (Sandbox Code Playgroud)
改变你的JS代码
function submitFormAjax(e)
{
e.preventDefault();
var xmlhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
}
......
................
...............
return false; //at last line
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12742 次 |
| 最近记录: |