Ajax表单提交

我正在使用ajax提交一个html输入表单,并在完成后重定向输出页面。 我尝试了两种方法,但不确定为什么他们的结果不同。

HTML表单看起来像这样:

方法1:

  var frm = $('#output_post'); frm.submit() $.ajax({ type: frm.attr('method'), url: frm.attr('action'), success: function (url) { window.location = "/output.html" } }); 

方法2:

  var frm = $('#output_post'); $.ajax({ type: "POST", url: frm.attr('action'), success: function(url) { window.location = "/output.html" } }); 

方法1按预期工作,但我在方法2中得到错误消息405 Method Not Allowed The method GET is not allowed for this resource. 方法1和方法2之间的区别是frm.submit() ,我非常确定这两种方法都能成功启动计算。

有人能给我一些关于这个问题的提示吗? 谢谢!

首先,我实际上会说.submit()会更好地保留允许浏览器实际执行跟随action=""的自然/缩进行为 – 如果你想实际拥有不同的’最终结果’ – 这就是$.submit()帮助的地方。

 /** * $.submit will listen to * the .submit event, preventing * default and allowing us to mimic * the submission process and have our * bespoke end result. **/ $('#output_post').submit(function(event) { event.preventDefault(); var getValues = $(this).serialize(); $.post( 'yourScript.php', getValues, function() { window.location.href = "/output.html"; } }); 

对该问题的评论

方法一

  • 这“离开”了这个function。 在允许执行脚本的其余部分之前,过早地将您从页面中移出。 本机.submit()将跟随操作,这是缩进的行为。 因此, $.ajax从未运行过。

方法二

  • 服务器可以/可以决定它接受的内容类型。
  • 没有数据被发送到URL ,因此 – 默认为GET (尽管类型: POST )但是没有序列化。 数组给出。
  • 如果您在方法二中定义“数据:值”,这可能会“行为”不同。

试试这个:

 var frm = $('#output_post'); $('#output_post').submit(function(event) { $.ajax({ type: "POST", url: frm.attr('action'), success: function(url) { window.location = "/output.html" } }); }); 

– 谢谢