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

时间:2013-06-14 14:44:01

标签: java ajax forms

我有一个网页表单,允许用户输入信息并提交。如果用户在表单中提交重复的id字段,表单应保留在那里并提示错误信息。但是现在,如果输入了一些错误信息,页面将被重定向到显示“HTTP状态409-冲突”的错误页面。我的表格是:

<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状态409-冲突”的错误页面?为什么ajax表单验证checkForm()在这里不起作用?

2 个答案:

答案 0 :(得分:1)

因为$.post(是异步的而您的return没有效果。表单始终提交给服务器,而行throw new WebApplicationException(409);会导致错误代码响应。

<强>更新

@ WouterH的建议应该有效。确保您在适当的时刻看到提醒:

function checkForm() {
    $.post("/myapp/rest/customer/created", function(data, status) {
      if (status === "200") {
        alert("post success");
        // redirect to destination
      } else {
        alert("post error");
        //display error information in the current form page
        $("#errorDiv").html("<font color=red>ID already exists!</font>");
      }
    });
    alert("form posted");
    return false;
}

更新2:

function checkForm() {
    $.post("/myapp/rest/customer/created", function(data, status) {
      alert("post handler, status=" + status); 
    });
    alert("form posted");
    return false;
}

答案 1 :(得分:1)

您的checkForm方法是异步的。或者更确切地说,它使用了异步函数$ .post。 $ .post使用AJAX,而AJAX代表Asynchronious Javascript和XML。这意味着,该函数在完成任务并调用回调之前立即返回($ .post)。

由于您使用AJAX提交,因此您始终希望阻止表单提交。你可以通过在checkForm中返回false而不是在提供给$ .post的回调中来做到这一点。

例如:

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;
}