1. 动态引入 polyfill
function scriptLoader(url) {
return new Promise((resolve,reject)=>{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type= 'text/javascript';
script.onload = ()=>resolve()
script.src = src;
head.appendChild(script);
})
}
// 注: 若要适配 ie, 需添加 state. onreadystatechange 事件
2. axios 发送 post 请求(json+file) 节选自github
var formdata = new FormData()
for (var pk in this.formItem) {
formdata.set(pk, this.formItem[pk])
}
formdata.set('file', this.file, this.file.name)
/* set和append区别
formData.set('a', 5)
formData.set('a', 6) // {a: 6}
formData.append('b', 5)
formData.append('b', 6) // {b: [5, 6]} */
axios({
method: 'post',
url: '//k-on.live:8081/api/std/submit',
headers: {
'Content-Type': 'multipart/form-data;chaset=UFT-8'
},
data: formdata,
onUploadProgress: progressEvent => { this.loading = progressEvent.loaded / progressEvent.total }
}).then(config => {
let { data } = config
if (data.success) {
this.$Modal.success({ content: data.message });
} else {
this.$Modal.warning({ content: data.message });
}
}).catch(() => {
this.$Modal.warning({ content: '网络错误,请重试' });
}).then(() => {
this.loading = 0
})
3.1 普通 GET 请求拿 json
3.2 普通 GET 请求拿文件
3.3 POST 请求传 json
3.4 文件上传
let btn = document.querySelector('#btn')
let file = document.querySelector('#file')
btn.onclick = () => file.click() // 调取系统选择图片的弹框
// 监听input的file变化值
file.onchange = function (event) {
let file = event.target.files[0]
upload(file)
}
function upload(file) {
let xhr = new XMLHttpRequest()
xhr.open('post', '/upload', true)
let formData = new FormData()
formData.set('filename', file)
xhr.send(formData)
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
alert('success')
}
}
}