【问题标题】:jQuery `submit` method ignores POST sends with GET. Why?jQuery `submit` 方法忽略使用 GET 发送的 POST。为什么?
【发布时间】:2013-11-26 14:02:38
【问题描述】:

我有一个这样的表格。

<form id="hiddenForm" method="post" action="/my-controller/my-action/" enctype="multipart/form-data">
    <input type="hidden" id="HiddenFormInput" name="HiddenFormInput">
</form>

它由通过https://[my-server]/my-controller/my-action/ 访问的网页生成,这也是表单指向的操作。

在服务器端,我区分了GETPOST 请求。页面要么简单地显示(GET),要么根据表单的值显示一些结果(POST)。

当我使用jQuery提交表单时(我这里没有使用AJAX,只是提交表单),就像这个sn-p一样,

$("#hiddenForm").submit();

然后 jQuery 似乎使用GET 提交此表单,尽管它明确标记为使用POST 提交。即使alert($("#hiddenForm").attr("method")); 总是产生"post"。但是,仅当页面已由 GET 加载时,才会发生这种不需要的行为。如果页面来自POST,即该表单已至少提交一次,则一切正常。

更新

问题出在一个普通的旧preventDefault() 上。触发提交的按钮有它自己的功能。这是一个超链接。所以我有这一系列的动作。

  1. 超链接到https://[my-server]/my-controller/my-action/#
  2. 提交带有操作https://[my-server]/my-controller/my-action/的表单。

当然,这会导致在没有提交表单的情况下调用GET。一旦我在页面https://[my-server]/my-controller/my-action/# 上,超链接就失去了它的功能。这就是为什么第二次尝试总是有效的原因,因为操作链被简化为提交表单。

  1. 指向https://[my-server]/my-controller/my-action/#的超链接(无效,因为已经存在)
  2. 提交带有操作https://[my-server]/my-controller/my-action/的表单。

然后它当然起作用了。

【问题讨论】:

  • document.getElementById("hiddenForm").submit(); 是做什么的?
  • 你怎么知道页面是使用GET方法提交的?
  • 您是否尝试在表单中添加&lt;input type="submit" /&gt; 元素?
  • 我测试了一下,jQuery使用的提交方法“POST”。
  • 感谢preventDefault(),我也遇到过,需要咖啡。 :)

标签: javascript php jquery forms zend-framework


【解决方案1】:

正如 cmets 中所讨论的,没有错误,至少在 jQuery 2.0.3 的最后一个版本上,可以用这个进行测试:

<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
  $('#dosubmit').on('click',function(){
    $("#hiddenForm").submit();
  });
});
</script>
</head>
<body>

<?php
//
if(count($_GET) > 0) {
  echo "<textarea style=\"width: 700px; height: 90px;\">
Submitted with method=GET: \$_GET:
";
  var_dump($_GET);
  echo "</textarea>";
}

if(count($_POST) > 0) {
echo "<textarea style=\"width: 700px; height: 90px;\">
Submitted with method=POST: \$_POST:
";
  var_dump($_POST);
  echo "</textarea>";
}
?>

<form id="hiddenForm" method="post" enctype="multipart/form-data">
  <input type="hidden" id="HiddenFormInput" name="HiddenFormInput" />
</form>

<div id="dosubmit" style="background-color: gold; width: 200px; cursor: pointer;">Click me to Do jQuery Submit</div>

</body>
</html>

点击金色背景文字时,$("#hiddenForm").submit();用于提交表单。

这是输出:

Submitted with method=POST: $_POST:
array(1) {
  ["HiddenFormInput"]=>
    string(0) ""
}

在您的原始表单中,提交时不传递任何 URL 参数,因为仅提交具有指定名称属性的输入。所以我为你的隐藏输入添加了属性 name="HiddenFormInput"。

【讨论】:

    猜你喜欢
    • 2015-09-07
    • 1970-01-01
    • 2015-08-06
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    相关资源
    最近更新 更多