java - 如何在不重定向的情况下处理表单提交错误?

标签 java ajax forms

我有一个网络表单,允许用户输入信息并提交。如果用户在表单中提交了重复的 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/

相关文章:

java - JPA getSingleResult() 或 null

javascript - 如何使Code Igniter ajax请求URL出现在浏览器URL中。

javascript - 如何使用 ajax 发送对象数组和其他表单数据?

python - 一个 html 表单,几个相互关联的 django 表单 - 如何保存?

java - freemarker 中的嵌套变量赋值

java - TextView 颜色设置问题

java - 非阻塞 Java 异步处理 - 如何限制内存使用?

javascript - 我可以使用 AJAX 从不同的文件/ View /页面加载代码,以便我可以执行类似于 SPA 的操作吗?

php - 在 codeigniter 中处理多个复选框数组

javascript - Vuetify/Vuejs 单选组和复选框组设置为相同的 v-model