純粋なJavaScript フォームなしでPOSTデータを送信する 質問する

純粋なJavaScript フォームなしでPOSTデータを送信する 質問する

$.post()フォームを使用せず、純粋な JavaScript (jQuery ではない)のみを使用してページを更新せずに POST メソッドを使用してデータを送信する方法はありますか? おそらくあるでしょうhttprequest、または何か他の方法 (今は見つけられません)?

ベストアンサー1

これを送信して、本文にデータを挿入することができます:

var xhr = new XMLHttpRequest();
xhr.open("POST", yourUrl, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
    value: value
}));

ちなみに、get リクエストの場合:

var xhr = new XMLHttpRequest();
// we defined the xhr

xhr.onreadystatechange = function () {
    if (this.readyState != 4) return;

    if (this.status == 200) {
        var data = JSON.parse(this.responseText);

        // we get the returned data
    }

    // end of state change: it can be after some time (async)
};

xhr.open('GET', yourUrl, true);
xhr.send();

おすすめ記事