问题
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