FormDataオブジェクトを送信
FormDataオブジェクトを送信には、XMLHttpRequestオブジェクトやfetchメソッドを使用します。
FormDataオブジェクトをリクエストボディとして指定することで、送信することができます。
サンプルコード(XMLHttpRequest)
JavaScript (ES5)
var formData = new FormData();
// キーと値のペアを追加
formData.append('foo', 'abc');
var xhr = new XMLHttpRequest();
xhr.open('post', 'api.php');
xhr.addEventListener('readystatechange', function() {
if (xhr.readyState === 4 && (xhr.status < 300 || xhr.status === 304)) {
alert(xhr.response);
}
};
// FormDataを送信
xhr.send(formData);
JavaScript (ES6以降)
const formData = new FormData();
// キーと値のペアを追加
formData.append('foo', 'abc');
const xhr = new XMLHttpRequest();
xhr.open('post', 'api.php');
xhr.addEventListener('readystatechange', () => {
if (xhr.readyState === 4 && (xhr.status < 300 || xhr.status === 304)) {
console.log(xhr.response);
}
};
// FormDataを送信
xhr.send(formData);
サンプルコード(Fetch API)
JavaScript
const formData = new FormData();
// キーと値のペアを追加
formData.append('foo', 'abc');
const xhr = new fetch('api.php', {
method : 'post',
body : formData
});