Vue表单使用v-on:submit提交为空、加.prevent修饰符重复提交两次求助
问题修复方案
问题根源说明
- 不加
.prevent时表单提交空数据:是因为没有阻止浏览器原生表单提交的默认行为,页面会在你的axios异步请求完成前刷新,所以看不到有效提交数据,只有原生无数据的提交记录。 - 加
.prevent后重复提交:是CoreUICForm组件的内置submit事件逻辑和type="submit"的按钮双重触发导致的,相当于同一个提交动作触发了两次postdata回调。
具体修改步骤
- 模板部分修改
<!-- 1. 表单提交加.prevent,阻止原生提交 --> <CForm id="myforma" @submit.prevent="postdata"> <!-- 2. 修正writer输入框的语法错误,v-model前多写的冒号删掉 --> <CInput name="writer" label="writer" placeholder="Enter the writer" v-model="posts.writer" /> <!-- 3. 提交按钮修改type为button,绑定点击事件触发提交,避免双重触发 --> <CButton type="button" size="sm" color="primary" @click="postdata"><CIcon name="cil-check-circle" /> Submit</CButton>
如果你不想改按钮类型,也可以给CForm加@submit.native.prevent,直接监听原生submit事件而不是组件封装的事件,也能解决重复触发问题。
- JS逻辑调整
你当前postdata方法里请求完成后直接把this.posts赋值为后端返回值,但你的PHP接口没有返回有效表单数据,会直接清空你的表单内容,建议调整为:
postdata() { // 提交前先打印确认数据是否正确 console.log('提交的数据:', this.posts) axios.post('http://localhost/post.php',this.posts) .then((response) => { console.log('提交成功返回:', response.data) // 提交成功后如果需要重置表单,手动清空,不要直接用返回值覆盖 this.posts = { title: '', year :'' , writer:null, description:null, type: '1.Books' } }) }
- PHP接口修复
当前代码存在SQL注入风险,且没有返回正确的JSON格式,修改为:
<?php include "db.php"; $received_data = json_decode(file_get_contents("php://input"),true); // 先判空避免报错 if(empty($received_data['title'])){ echo json_encode(['code'=>400, 'msg'=>'标题不能为空']); exit; } $table= $received_data['title']; $wri=$received_data['writer'] ?? ''; // 使用参数化查询避免SQL注入 $result=pg_query_params($connection,"INSERT INTO tablet (title) VALUES ($1)", [$table]); if($result){ echo json_encode(['code'=>200, 'msg'=>'提交成功']); }else{ echo json_encode(['code'=>500, 'msg'=>'提交失败:'.pg_last_error($connection)]); } ?>
内容的提问来源于stack exchange,提问作者thanostav
相关产品推荐
相关产品推荐

