我有一个网络表单,允许用户输入信息并提交。如果用户在表单中提交了重复的 id 字段,则表单应保留在那里并提示错误信息。但是现在如果输入一些错误信息,页面将被重定向到显示“HTTP Status 409 - Conflict”的错误页面。我的表格是:
<form action="/myapp/rest/customer/created" onsubmit="return checkForm();" method="POST">
<table border="1">
<tr>
<td>Customer name:</td>
<td><input type="text" id="name" name="name"></td>
</tr>
<tr>
<td>Customer ID:</td>
<td><input type="text" id="id" name="id"></td>
</tr>
<tr>
<td>Customer DOB:</td>
<td><input type="text" id="dob" name="dob"></td>
</tr>
</table>
<br/>
<input type="submit" value="Submit">
</form>
<div><span id="errorDiv" class="errorDiv" ></span></div>
JavaScript 函数 checkForm()
是:
function checkForm() {
$.post("/myapp/rest/customer/created", function(data, status) {
if (status === "200") {
// redirect to destination
return true;
} else {
//display error information in the current form page
$("#errorDiv").html("<font color=red>ID already exists!</font>");
return false;
}
});
}
后端服务是Java REST API,如果输入并提交一些错误信息,它会捕获异常:
@Path("/customer")
public class CustomerService {
@Context UriInfo uriInfo;
@Context HttpServletRequest request;
@Context HttpServletResponse response;
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
CustomerJDBCTemplate dbController = (CustomerJDBCTemplate) context.getBean("customerJDBCTemplate");
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("created")
public Response createCustomer(@FormParam("id") int id,
@FormParam("name") String name, @FormParam("dob") Date dob)
throws ServletException, IOException, WebApplicationException {
URI uri = URI.create(uriInfo.getPath());
Response r;
r = Response.created(uri).build();
try {
dbController.create(id, name, dob); //This may throw exception.
request.setAttribute("name", name);
request.setAttribute("dob", dob);
request.setAttribute("id", Integer.valueOf(id));
RequestDispatcher dispatcher = request.getRequestDispatcher("/confirm.jsp");
dispatcher.forward(request, response);
} catch (DataAccessException ex) {
throw new WebApplicationException(409);
}
return r;
}
}
为什么用户提交错误信息后,页面总是重定向到显示“HTTP Status 409 - Conflict”的错误页面?为什么 ajax 表单验证 checkForm()
在这里不起作用?
最佳答案
您的 checkForm 方法是异步的。或者更确切地说,它使用异步函数 $.post。 $.post 使用 AJAX,AJAX 代表异步 Javascript 和 XML。这意味着该函数在完成其任务并调用回调之前立即返回($.post)。
您总是希望阻止表单提交,因为您是使用 AJAX 提交的。您可以通过在 checkForm 中返回 false 来完成此操作,而不是在提供给 $.post 的回调中返回 false。
例如:
function checkForm() {
$.post("/myapp/rest/customer/created", function(data, status) {
if (status === "200") {
// redirect to destination
} else {
//display error information in the current form page
$("#errorDiv").html("<font color=red>ID already exists!</font>");
}
});
return false;
}
关于java - 如何在不重定向的情况下处理表单提交错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17111124/