首页 > 解决方案 > 用两个动作提交相同的表格?

问题描述

我有一个表单可以通过 POST 提交数据并将数据发送到 2 个页面。

我已经用javascript尝试了代码。一个表单提交工作,但另一个提交不工作

<form id="add">
    <input type="text" name="test">
    <input type="submit" onclick="return Submit();">
</form>

javascript

function SubmitForm()
{
     document.forms['add'].action='filecreate.php';
     document.forms['add'].submit();
     document.forms['add'].action='filecreate.fr.php';
     document.forms['add'].submit();
     return true;
}

第一次提交无效,但第二次提交有效。

标签: javascriptphpjquery

解决方案


由于您似乎将完全相同的数据发送给两个不同的处理程序,因此您可以掷硬币 - 并说您只提交一个表单,并在filecreate.php.

当您发送表单时,您不能在同一个 HTTP 请求中发送两个单独的表单 - 因此您可以通过异步方法同时执行它们,或者在提交一个表单后同时在后端处理它们。

由于您没有显示任何 PHP 代码,我正在做一些假设并编写一些伪代码,但这应该足以让您入门。

因此,首先,为您的表单设置一个静态操作属性。

<form id="add" action="filecreate.php">
   <input type="text" name="test">
   <input type="submit">
</form>

如果您通过 POST 发送它,那么您还需要指定方法,

<form id="add" action="filecreate.php" method="POST">

然后,在 PHP 中,如果将两个文件包含到另一个文件中,则可以执行这两个文件。意思是,在您的 中filecreate.php,您包括filecreate.fr.php. 一旦你这样做了,该文件的内容也将被执行。

<?php 
// Once you require the file, it will be executed in place
require "filecreate.fr.php";

// .. handle the rest of your normal execution here.

也就是说,如果您多次执行非常相似的事情,只是使用不同的数据,您可能希望为它创建函数 - 遵循 DRY 原则(“不要重复自己”),您可能可以创建一个函数处理结构和处理,然后通过该函数分别发送数据。


推荐阅读