- ajax
-
/** * Created by kjf on 2019-03-25. * * axios.request(config) axios.get(url[, config]) axios.post(url[, data[, config]]) axios.delete(url[, config]) axios.head(url[, config]) axios.options(url[, config]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]]) */ import axios from 'axios'; export default function (url, data = {}, method = 'GET', params, headers) { return new Promise((resolve, reject) => { let promise = null; if (method === 'GET') { promise = axios.get(url, {params: data, headers}); } else if (method === 'POST') { promise = axios.post(url, data, {params: params, headers}); } promise .then(response => resolve(response)) .catch(err => { // console.log("/src/axios/ajax.js----error: "+err) reject(err); }); }); }
1. 直接用 Ajax 發 POST/GET 請求
錯誤的方式:
-
export const requestDownloadLabFile = (id) => { // 下載附件 const url = preFixed + '/lab/myExperimentOperator/download/' + id; return ajax(url, {}, 'GET', {}, {'labAuth': 'http://localhost:7000'}); };
正確的方式:(缺點: 必須要知道 文件名.類型,意味着后端必須給到 這樣的一個字段)
-
export const requestDownloadLabFile = (id) => { // 下載附件 const url = preFixed + '/lab/myExperimentOperator/download/' + id; ajax(url, {}, 'GET', {}, {'labAuth': 'http://localhost:7000'}).then(res=> { const content = res.data; const blob = new Blob([content]); const fileName = 'fileName.type'; if ('download' in document.createElement('a')) { // 非IE下載 const elink = document.createElement('a'); elink.download = fileName; elink.style.display = 'none'; elink.href = URL.createObjectURL(blob); document.body.appendChild(elink); elink.click(); URL.revokeObjectURL(elink.href); // 釋放URL 對象 document.body.removeChild(elink); } else { // IE10+下載 navigator.msSaveBlob(blob, fileName); } }); return 0; }
2. window.open 此類方法,兼容性不好
-
export const requestDownloadLabFile = (id) => { // 下載附件 const url = preFixed + '/lab/myExperimentOperator/download/' + id; window.open(url, '_blank'); // 新打開窗口 };
3. form 當前頁下載: (當 鏈接失效 時,影響當前頁, 但是可以接受)____推薦使用
- diyDownload
-
export const diyDownload = (url, data, method = 'GET') => { const body = document.getElementsByTagName('body')[0]; const form = document.createElement('form'); form.method = method; form.action = url; for (let key in data) { let param = document.createElement('input'); param.type = 'hidden'; param.name = key; param.value = data[key]; form.appendChild(param); } body.appendChild(form); form.submit(); body.removeChild(form); };
-
export const requestDownloadLabFile = (id) => { // 下載附件 const url = preFixed + '/lab/myExperimentOperator/download/' + id; diyDownload(url, {}, 'GET'); };
4. iframe 標簽下載: (當 鏈接失效 時,不會影響當前頁)
-
export const requestDownloadLabFile = (id) => { // 下載附件 const url = preFixed + '/lab/myExperimentOperator/download/' + id; try { let elemIF = document.createElement('iframe'); elemIF.src = url; elemIF.style.display = 'none'; document.body.appendChild(elemIF); } catch (e) { myConsole('下載異常!'); } };