2013-06-18 84 views
0

我有一个web表单让用户输入一些信息并提交。我想要这样的行为,如果提交成功,它会转到一个页面。但是如果有一些表单提交错误(在我的情况下是由于现有的ID),我希望表单停留在那里而不会进入下一页,并提醒用户“ID已经存在”。我用jQuery来处理成功和失败的事件:在jQuery中处理表单提交

function checkForm() { 

$.post("/myapp/rest/customer/created", $("form").serialize(), function(
    data, status) { }) 
.done(function() {alert("post success");}) 
.fail(function() {alert("post error");}); 
return false; 
} 

我的形式是:

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

提交后,无论提交是否是成功还是失败,我只看到弹出消息框说“发布成功”或“发布错误”。但如果成功,它将永远不会进入下一页。我甚至尝试像下面的代码不同的方法,但它没有工作,要么:

function checkForm() { 
    $.post("/myapp/rest/customer/created", function(data, status) { 
     if (status === "success") { 
     alert("post success"); 
     } else { 
     alert("post error"); 
     } 
    }); 

    return false; 
} 

那么如何纠正它,使其重定向到下一个页面(/myapp/rest/customer/created)如果提交成功?

+0

你总是返回false。 – j08691

+0

@ j08691:我不能根据状态返回真/假,因为如果我这样做,它总是会直接指向下一页。 – tonga

+0

返回false就好了。你只需要重定向用户window.location.href ... –

回答

1

您可以将成功的条件使用window.location.href内重定向:

if (status === "success") { 
    window.location.href = 'http://url.com' 
} 
+0

谢谢马修。我使用这种方法,它的工作原理。但是...提交成功后,它显示一个错误页面:HTTP状态405 - 方法不允许。是什么导致这个问题? – tonga

+0

但是...什么?大声笑 –

+0

这意味着任何URL你重定向到不允许GET。 –