我一直在尝试弄清楚如何一起使用 VueJS、Axios 和 Python。我可以向 python 文件发出 post 请求。当我单击提交按钮时,响应数据显示正确,但只显示一秒钟,然后消失。这是为什么?
插入.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>
默认按钮类型是“提交”,这会导致页面刷新。
或者,您可以使用 .prevent 修饰符。
<button v-on:click.prevent="submit">Submit</button>
关于javascript - 将VueJS与Axios一起使用后响应数据消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46100652/