【问题标题】:Using VueJS with Axios post response data disappears使用 VueJS 和 Axios 后响应数据消失
【发布时间】:2018-02-16 10:42:13
【问题描述】:

我一直在尝试弄清楚如何将 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>

【问题讨论】:

    标签: javascript python vue.js python-3.6 axios


    【解决方案1】:

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

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

    默认按钮类型是“提交”,它会刷新您的页面。

    您也可以使用 .prevent 修饰符。

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

    【讨论】:

    • 嗯,这很有道理,不敢相信我没有想到这一点。我想知道为什么页面每次都刷新。愚蠢的错误,非常感谢!省得我头疼,我还以为我用 VueJS/Axios 做错了!
    • @antfuentes87 去过那里:)
    猜你喜欢
    • 2020-03-22
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-19
    • 2017-06-21
    • 2020-07-03
    相关资源
    最近更新 更多