使用 VueJS with Axios post 响应数据消失

Using VueJS with Axios post response data disappears

我一直在努力弄清楚如何一起使用 VueJS、Axios 和 Python。我可以向 python 文件发出 post 请求就好了。当我点击提交按钮时,响应数据正确显示,但只有一秒钟然后消失了。这是为什么?

insert.py

#!/usr/bin/python3.6
import os
import sys
import json

parsed_json = json.loads(sys.stdin.read())    
print ("Content-type: text/html\n")
print(parsed_json['firstName'])
print(parsed_json['lastName'])

index.html

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>index.html</title>
 </head>
 <body>
  <form id="example-1">
   <input type="text" ref="firstName">
   <input type="text" ref="lastName">
   <button v-on:click="submit">Submit</button>
   {{ output }}
  </form>
  <script src="https://unpkg.com/vue@2.4.2/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
   var example1 = new Vue({
    el: '#example-1',
    data: {
     output: ''
    },
    methods: {
     submit: function () {
      axios.post('/cgi-bin/insert.py', {
       firstName: this.$refs.firstName.value,
        lastName: this.$refs.lastName.value
      })
      .then(response => {
       this.output = response.data;
      })
      .catch(function (error) {
       console.log(error);
      });
     }
    }
   }) 
  </script>
 </body>
</html>

将您的按钮更改为 type="button"

<button type="button" v-on:click="submit">Submit</button>

默认按钮类型是 "submit",它会刷新您的页面。

或者您可以使用 .prevent 修饰符。

<button v-on:click.prevent="submit">Submit</button>