我們經常使用表單來上傳數據,以及上傳文件,那么怎么在表單提交成功的時候接受服務器的響應,并作出相應操作.
當然使用一般jQuery上傳對象的格式也是可以的,如果使用傳統的表單上傳呢?
<!DOCTYPE html><html lang="en"> <head> <title></title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <form method="post" action="/upload" enctype="multipart/form-data"> <input type="text" name="name" value="" placeholder="請輸入用戶名"> <input type="text" name="age" value="" placeholder="請輸入年齡"> <input type="file" name="uploadFile"> <input type="submit" value="提交"> </form> </body></html>
這種方式可以提交,那么問題來了,表單提交以后如果需要獲取服務器的響應呢,如果需要在響應成功后跳轉頁面呢,這種方式顯得不好處理.
切回正題,在vue中這種簡單的表單提交如何處理呢,其實使用的是 FormData 來模擬表單提交
<head> <title></title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://cdn.bootcss.com/vue/2.3.4/vue.js"></script> <script src="https://cdn.bootcss.com/axios/0.16.2/axios.js"></script></head><body> <form> <input type="text" value="" v-model="name" placeholder="請輸入用戶名"> <input type="text" value="" v-model="age" placeholder="請輸入年齡"> <input type="file" @change="getFile($event)"> <button @click="submitForm($event)">提交</button> </form> <script> window.onload = function () { Vue.prototype.$http = axios; new Vue({ el: 'form', data: { name: '', age: '', file: '' }, methods: { getFile(event) { this.file = event.target.files[0]; console.log(this.file); }, submitForm(event) { event.preventDefault(); let formData = new FormData(); formData.append('name', this.name); formData.append('age', this.age); formData.append('file', this.file); let config = { headers: { 'Content-Type': 'multipart/form-data' } } this.$http.post('/upload', formData, config).then(function (res) { if (res.status === 2000) { /*這里做處理*/ } }) } } }) } </script></body></html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答