You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用API设置表单值后如何自动提交,提交地址不符合预期如何解决

调用API后自动提交表单的修复方案

根因说明

Vue的响应式数据更新后,DOM渲染是异步批量执行的。你在接口请求成功的回调中同步给urlLogin赋值后,立刻调用this.$refs.form.submit()时,form标签的action属性还未被Vue更新为接口返回的后端地址,空的action属性会默认让表单提交到当前前端页面地址,就是你遇到的地址不符问题。

修复方案

在$nextTick回调中执行提交操作,等待DOM更新完成后再触发表单提交:

<template>
  <!-- Sing in  Form -->
  <section class="sign-in" style="padding-top: 65px">
    <div class="container">
      <form :action="urlLogin" method="post" ref="form">
        <input type="text" id="SAMLRequest" name="SAMLRequest" v-model="SAMLRequest">
        <input type="submit" value="Submit">
      </form>
    </div>
  </section>
</template>

<script>
import axios from 'axios';

export default {
  name: 'LoginPage',
  data() {
    return {
      urlLogin: '',
      SAMLRequest: ''
    }
  },
  mounted() {
    axios.get(`http://localhost:8080/rest/v2/sso/loginInfo`)
        .then(response => {
          this.urlLogin = response.data.urlLogin;
          this.SAMLRequest = response.data.samlrequest;
          // 等待DOM更新完成后再提交表单
          this.$nextTick(() => {
            this.$refs.form.submit();
          })
        })
        .catch(e => {
          console.log(e)
        })
  }
}
</script>

额外注意事项

请确认接口返回的urlLogin是带完整协议前缀的地址,比如http://localhost:8080/login,如果返回值省略了http:///https://前缀,浏览器会将其识别为相对路径,依然会拼接在当前前端域名后提交,导致地址错误。

内容的提问来源于stack exchange,提问作者Sakura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 22:54:03