FormData doesn't include value of buttons

心不动则不痛 提交于 2019-12-10 15:09:47

问题


Consider the following snippet:

$('#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>

(Have your developer tools open and watch for HTTP requests.)

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.

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


回答1:


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>


来源:https://stackoverflow.com/questions/48322876/formdata-doesnt-include-value-of-buttons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!