使用jQuery生成POST表单并处理结果


POST form with jQuery and handle the result

是否可以通过jQuery POST表单并处理结果?(不使用json、ajax等)。

类似这样的东西:

<form id="loginform">
      //some input fields and a submit button.
</form>

然后从jQuery:

$("#loginform").submit(function (e) {
   $.post("somePHPscript")
   .done(function (response) {  
        //Handle response
});
});

还是说,这就等于删除表单,将事件绑定到提交按钮,然后手动输入?

我不太清楚为什么你想要一个通过覆盖默认表单操作而不使用ajax等来处理提交结果的表单。

您需要阅读以下内容:http://api.jquery.com/submit/它将概述如何捕获表单提交事件,您可以通过使用上面链接中概述的event.preventDefault()来阻止移动到另一个页面。

您拥有的代码将处理响应。你只需要用它做点什么。如果你返回一系列文本,你可以做这样的事情:

.done(function(response){
  alert(response);
});

如果你要返回一些HTML,可能是这样的:

.done(function(response){
  $(response).insertAfter('div');
});

编辑

当然,如果您提交了表单,那么尝试从服务器检索响应是没有意义的。但现在您的代码正在提交表单并尝试执行AJAX请求。不妨停止表单提交和执行AJAX请求,这样您就可以对响应进行处理。

<form id="the-form" role="form"> 
  <input type="button" id="button-form">
</form>
$("#button-form").on('click', function (e) {    
   e.preventDefault();
   $.post($("#the-form").attr('action'), function(response) {console.log(response)});
});