【发布时间】:2018-06-27 14:51:15
【问题描述】:
考虑以下 sn-p:
$('#myBtn').click(function(e) {
e.preventDefault();
var formElement = $(this).closest('form')[0];
var request = new XMLHttpRequest();
request.open("POST", "https://posttestserver.com/post.php");
request.send(new FormData(formElement));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" action="https://posttestserver.com/post.php">
<input type="text" name="wtf" />
<button type="submit" name="lol" value="cats" id="myBtn">
Huh
</button>
</form>
(打开您的开发者工具并观察 HTTP 请求。)
当您单击按钮时,您在文本框中输入的任何文本都会包含在 POST 请求中。但是,按钮本身的 lol=cats 对不是。
如何让FormData 包含按钮给出的数据?
【问题讨论】:
-
按钮不是输入类型,因此无法将值传递给 POST 请求
-
您是否在 Firefox 中进行测试?检查这个问题:stackoverflow.com/questions/38277900/…
-
@RoryMcCrossan:Chrome 但在 FF 中相同
-
@RoryMcCrossan:接受的答案似乎准确地描述和解释了这里发生的事情
-
在这种情况下,其他浏览器可能已更新以遵循该标准。老实说,我一直发现在请求中发送提交按钮值的支持有点不稳定。如果可能,我会手动将其添加到请求中。
标签: javascript jquery html form-data