纯 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
}));

顺便说一句,对于获取请求:

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();

答案 2

Fetch API旨在使GET请求变得容易,但它也能够发布。

let data = {element: "barium"};

fetch("/post/data/here", {
  method: "POST",
  headers: {'Content-Type': 'application/json'}, 
  body: JSON.stringify(data)
}).then(res => {
  console.log("Request complete! response:", res);
});

如果你像我一样懒惰(或者只是喜欢快捷方式/助手):

window.post = function(url, data) {
  return fetch(url, {method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data)});
}

// ...

post("post/data/here", {element: "osmium"});