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

Laravel中如何实现单表单按点击按钮提交至不同路由

实现表单按不同按钮提交到不同路由

要实现点击不同按钮提交到对应路由,核心是阻止按钮默认的表单提交行为,再动态修改表单的action属性后手动提交。以下是修改后的完整代码:

{{ Form::open(['url'=> route('finance.invoices.store', ['pending', 'visit_id' => $visit->id]), 'id'=>'inv', 'method' => 'POST']) }}
    <script>
    $(document).ready(function() {
        // Button 1(Proforma)的提交逻辑
        $("#proforma").click(function(e) {
            // 阻止按钮默认提交行为,避免用初始路由提交
            e.preventDefault();
            if ($("#inv").length) {
                // 替换为Button 1对应的目标路由1
                $("#inv").attr("action", "{{ route('finance.invoices.proforma', ['visit_id' => $visit->id]) }}");
                console.log("Send to Proforma button clicked");
                // 手动提交表单
                $("#inv")[0].submit();
            } else {
                console.log('Form not found');
            }
        });

        // Button 2(Bill)的提交逻辑
        $("#bill-btn").click(function(e) {
            // 同样阻止默认提交行为
            e.preventDefault();
            if ($("#inv").length) {
                // 设置Button 2对应的目标路由2
                $("#inv").attr("action", "{{ route('finance.invoices.store', ['pending', 'visit_id' => $visit->id]) }}");
                console.log("Bill Selected Items button clicked");
                // 手动提交表单
                $("#inv")[0].submit();
            } else {
                console.log('Form not found');
            }
        });
    });
    </script>

    <v-btn type="submit" id="proforma" color="warning" class="px-2">
        <i class="fa fa-money pr-2"></i>button 1
    </v-btn>
                
    <v-btn type="submit" id="bill-btn" color="success" class="px-2">
        <i class="fa fa-money pr-2"></i> button 2
    </v-btn>
</v-card-actions>

<input type="hidden" name="removedItems" />

{{ Form::close() }}

关键修改说明:

  • 阻止默认行为:给两个按钮的点击事件添加e.preventDefault(),避免按钮自动触发表单的初始路由提交。
  • 动态设置路由:在每个按钮的逻辑中,将表单action替换为对应按钮的目标路由(请把route('finance.invoices.proforma', ...)替换成你实际的路由1名称)。
  • 手动提交表单:修改完路由后,调用$("#inv")[0].submit()触发表单提交。

注意:需确保Laravel路由文件中已定义这两个目标路由,且参数传递正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 05:03:17