HTTP GET 方法
HTTP(超文本传输协议)提供客户端和服务器之间的通信,作为请求和应答。
HTTP 的 GET 方法从指定来源请求数据。
GET 请求可以被缓存并保留在浏览器历史记录中。
它也可以添加书签。
处理敏感数据时不应使用 GET 方法。
GET 请求有长度限制,只能用于获取数据。
浏览器提供了一个 XMLHttpRequest 对象,用于从 JavaScript 发出 HTTP 请求。
在本教程中,我们将学习如何发出 HTTP GET 请求。
我们可以在不刷新页面的情况下从 URL 检索数据。
XMLHttpRequest 使 Web 页面能够在不中断用户的情况下更新页面的一部分。
function httpGet(theUrl) { let xmlHttpReq = new XMLHttpRequest(); xmlHttpReq.open("GET", theUrl, false); xmlHttpReq.send(null); return xmlHttpReq.responseText; } console.log(httpGet('https://onitroad.com/posts'));
XMLHttpRequest 以异步或者同步方式获取数据。
请求的类型由 XMLHttpRequest.open() 方法上设置的可选异步参数选择。
如果此参数返回 true 或者未指定,则异步处理 XMLHttpRequest;否则同步处理。
由于同步请求会生成警告,因此我们应该发出异步请求并在事件处理程序中处理响应:
function httpGetAsync(theUrl, callback) { let xmlHttpReq = new XMLHttpRequest(); xmlHttpReq.onreadystatechange = function () { if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) callback(xmlHttpReq.responseText); } xmlHttpReq.open("GET", theUrl, true); //true for asynchronous xmlHttpReq.send(null); } httpGetAsync('https://onitroad.com/posts', function(result){ console.log(result); });
日期:2020-06-02 22:16:22 来源:oir作者:oir