国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > JS > 正文

Vue axios 中提交表單數據(含上傳文件)

2024-05-06 16:47:13
字體:
來源:轉載
供稿:網友

我們經常使用表單來上傳數據,以及上傳文件,那么怎么在表單提交成功的時候接受服務器的響應,并作出相應操作.

當然使用一般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武林網。


注:相關教程知識閱讀請移步到JavaScript/Ajax教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 南平市| 义马市| 日土县| 乐昌市| 峨边| 香港 | 会东县| 萍乡市| 丹棱县| 蛟河市| 铜梁县| 信阳市| 庄河市| 恩施市| 陆丰市| 永德县| 望谟县| 博乐市| 麻阳| 临颍县| 林甸县| 昭通市| 新野县| 弥渡县| 湘乡市| 古蔺县| 韶关市| 房山区| 彭山县| 宣武区| 休宁县| 灵山县| 清涧县| 沾益县| 天台县| 新野县| 澄城县| 莱芜市| 江北区| 怀柔区| 民丰县|