Javascript原生无依赖XMLHttpRequest实现网络请求,HttpGet或者Post/FormData/JSON

2021-06-12 74点热度 0人点赞 0条评论

平常的前端项目,请求后端API基本上都是用的jQuery或者Axios等等框架,把Http请求封装好后,很方便的调用,但是有时候一个很简单的项目或者功能,并不想引入jQuery或者Axios等框架,要怎么做呢?

HttpGet请求

var httpRequest = new XMLHttpRequest();
// 第二个参数true,说明是异步请求
httpRequest.open('GET', 'http://example.com/api/xxx', true);
httpRequest.send(); 

httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState === 4 && httpRequest.status === 200) {
        // 得到请求结果
        var resp = httpRequest.responseText;
        console.log(resp);
    }
};


// 以下是同步请求示例
httpRequest.open("GET","http://example.com/api/xxx", false);
httpRequest.send();
// 一般来说不适用同步,同步的话,这里会阻塞,直到收到请求的返回结果或者请求超时
console.log(httpRequest.responseText);

HttpPost请求(FormData)

var httpRequest = new XMLHttpRequest();
httpRequest.open("POST", "http://www.example.com/api/yyy", true);
httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest.send("keywords=" + keyword + "&name=" + name);
httpRequest.onreadystatechange = () => {
    if (httpRequest.readyState == 4 && httpRequest.status == 200) {
        // 如果服务器返回的是JSON,可以用JSON.parse(httpRequest.responseText)
        console.log(httpRequest.responseText);
    }
}

HttpPost请求(Json)

var payload = new Object();//需要发送的JSONObject
payload.name = "Terry";
payload.age = 28;

var httpRequest = new XMLHttpRequest();
httpRequest.open("POST", "http://www.example.com/api/xxx", true);
httpRequest.setRequestHeader('Content-Type', 'application/json');
httpRequest.send(JSON.stringify(payload));

httpRequest.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log(this.responseText);
    }
}

 

 

admin

这个人很懒,什么都没留下

文章评论

*

code