我有一个这样的表格。
<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/
访问的网页生成,这也是表单指向的操作。
在服务器端,我区分GET
和POST
请求。要么页面简单地显示 (GET
),要么根据表单的值显示一些结果 (POST
)。
当我使用 jQuery 提交表单时(我在这里没有使用 AJAX,只是提交表单),如这个片段所示,
$("#hiddenForm").submit();
然后 jQuery 似乎使用 GET
提交此表单,尽管它明确标记为使用 POST
提交。即使是 alert($("#hiddenForm").attr("method"));
也总是产生 "post"
。但是,只有当页面已通过 GET
加载时才会发生这种不需要的行为。如果页面来自 POST
,即表单已经至少提交了一次,那么一切都按预期进行。
更新
问题是一个普通的旧 preventDefault()
问题。触发提交的按钮有它自己的功能。这是一个超链接。所以我有了这个 Action 链。
- 超链接到
https://[my-server]/my-controller/my-action/#
- 提交带有操作的表单
https://[my-server]/my-controller/my-action/
。
当然,这会导致在未提交表单的情况下调用 GET
。一旦我进入页面 https://[my-server]/my-controller/my-action/#
,超链接就失去了它的功能。这就是第二次尝试总是成功的原因,因为操作链被简化为提交表单。
超链接到(无效,因为已经存在)https://[my-server]/my-controller/my-action/#
- 提交带有操作的表单
https://[my-server]/my-controller/my-action/
。
当然成功了。
最佳答案
正如评论中讨论的那样,没有错误,至少在最新版本的 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"。
关于javascript - jQuery `submit` 方法忽略使用 GET 发送的 POST。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20219181/