FormData不包含按钮的值 [英] FormData doesn't include value of buttons

查看:77
本文介绍了FormData不包含按钮的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

$('#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 对不是。

When you click on the button, any text you entered into the textbox is included in the POST request. However, the lol=cats pair from the button itself is not.

如何使 FormData 包含按钮给出的数据?

How can I make FormData include the data given by buttons?

推荐答案

因为对 FormData 的构造函数的调用不知道它是由一个触发的单击提交按钮(更不用说它是哪个提交按钮),并且因为您只想包含使用提交按钮的值,所以提交按钮不包含在发布的数据中。您可以使用 FormData.append 来包含所需的对。

Because the call to FormData's constructor doesn't know that it was triggered by a click on a submit button (let alone which submit button it was), and because you only want the used submit button's values included, the submit button isn't included in the posted data. You can use FormData.append to include desired pair.

$('#myBtn').click(function(e) {
    e.preventDefault();
    var formElement = $(this).closest('form')[0];
    var formData = new FormData(formElement);
    formData.append("lol","cats");
    var request = new XMLHttpRequest();
    request.open("POST", "https://posttestserver.com/post.php");
    request.send(formData);
});

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
 <form method="POST" action="https://posttestserver.com/post.php">
      <input type="text" name="wtf" />
      <button type="submit" id="myBtn">
        Huh
      </button>
    </form>

这篇关于FormData不包含按钮的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆