原生JS如何发送POST请求?XMLHttpRequest来帮忙

平常用 jQueryAjax 请求习惯了,忘记了原生 JS 发送请求的方式,复习一下

var url = "http://localhost:8080/login";
var httpRequest = new XMLHttpRequest();
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader("Content-type", "application/json");
var obj = {
    "username": "mkii",
    "password": "1234"
};

httpRequest.send(JSON.stringify(obj));

// 响应后的回调函数
httpRequest.onreadystatechange = function () {
    if (httpRequest.readyState == 4 && httpRequest.status == 200) {
        var json = httpRequest.responseText;
        console.log(json);
    }
};

你可能感兴趣的:(JavaScript,javascript)