纯Javascript发送没有表单的帖子数据 [英] Pure Javascript send post data without a form
本文介绍了纯Javascript发送没有表单的帖子数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法使用post方法发送数据而没有表单而没有刷新页面只使用纯Javascript(不是jQuery $ .post()
)?也许是httprequest或其他东西,现在找不到它。
Is there a way to send data using post method without a form and without refreshing page using only pure Javascript (not jQuery $.post()
)? Maybe httprequest or something else, just can't find it now.
推荐答案
你可以发送它并将数据插入正文:
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发送没有表单的帖子数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文