有没有一种方法可以使用 POST 方法发送数据而无需使用表单并且仅使用纯 JavaScript(不是 jQuery $.post()
)刷新页面?也许是 httprequest
或者别的什么(只是现在找不到)?
Is there a way to send data using the POST method without a form and without refreshing the page using only pure JavaScript (not jQuery $.post()
)? Maybe httprequest
or something else (just can't find it now)?
可以发送并插入数据到body:
You can send it and insert the data to the body:
var xhr = new XMLHttpRequest();
xhr.open("POST", yourUrl, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
value: value
}));
顺便说一下,获取请求:
By the way, for get request:
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();
这篇关于纯 JavaScript 发送没有表单的 POST 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!