有时候,我们无法借助熟悉的jquery发起请求,原生JS里是支持fetch函数的,这是个高度封装的方法,帮助我们做了很多底层的封装,下面列举一些发起请求的示例:
1-发起Get请求:
//httpGet请求 var httpGet = async function (getUrl) { var opts = { method: "GET", credentials: ‘include‘ // 强制加入凭据头 } await fetch(getUrl, opts).then((response) => { return response.text(); }).then((responseText) => { result = responseText; }).then((error) => { }); return result; };
2-发起Get文件流-支持设置保存文件名-下载:
//执行httpGet下载 var httpDownLoadFile = async function (getUrl, fileName) { var opts = { method: "GET", credentials: ‘include‘ // 强制加入凭据头 } await fetch(getUrl, opts).then((response) => { return response.blob(); }).then((blob) => { var url = window.URL.createObjectURL(blob); var a = document.createElement(‘a‘); a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); }).then((error) => { }); };
原文地址:https://www.cnblogs.com/lxhbky/p/12620086.html
时间: 2024-10-16 16:10:38