有時候,我們無法借助熟悉的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.uj5u.com/qiye/137194.html
標籤:JavaScript
