纯 JavaScript 在没有表单的情况下发送 POST 数据 [英] Pure JavaScript Send POST Data Without a Form

查看:33
本文介绍了纯 JavaScript 在没有表单的情况下发送 POST 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在没有表单的情况下使用 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 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆