Home JS发送POST JSON格式请求
Post
Cancel

JS发送POST JSON格式请求

var xhr = new XMLHttpRequest();
var sendData = {name:"abc"};
xhr.open("POST", "/service/hello", true);
xhr.setRequestHeader('content-type', 'application/json');
// 将用户输入值序列化成字符串
xhr.send(JSON.stringify(sendData));
// 回调
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        // 根据服务器的响应内容格式处理响应结果
        if(xhr.getResponseHeader('content-type') === 'application/json') {
            var result = JSON.parse(xhr.responseText);	
            // 根据返回结果判断验证码是否正确
            if(result.code === -1) {
                alert('验证码错误');
            }
        }
    } else {
        console.log(xhr.responseText);
    }
}

参考:js 发送post json格式请求

This post is licensed under CC BY 4.0 by the author.