使用一种形式将相同的输入发送到不同的操作

Send same inputs to different actions with one form

我有两个输入字段,我想 post 将相同的数据发送到两个不同的 php 文件,具体取决于单击的按钮。

在我的例子中,数据仅进入 foo.php,而不进入 excel.php

如果按下第二个按钮,我希望数据转到 excel.php。


JS:

$(function() {

  $("#from").datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 3,
    onClose: function(selectedDate) {
      $("#to").datepicker("option", "minDate", selectedDate);
    }
  });

  $("#to").datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 3,
    onClose: function(selectedDate) {
      $("#from").datepicker("option", "maxDate", selectedDate);
    }
  });

});

HTML:

<form action="foo.php" method="post">
     <label for="from">From</label>
     <input type="text" id="from" name="from" />

     <label for="to">to</label>
     <input type="text" id="to" name="to" /> <br>

     <input type="submit" value="Viewchart">
</form>

<form action="excel.php" method="post">
     <input type="submit" value="Download Excel file">
</form>

发生这种情况是因为您有一个带有 action="foo.php" 的表单。在这种情况下,无论您单击哪个按钮,它都会始终将数据发送到表单的操作 "foo.php"。
解决方案:
将输入分成两种形式,将第二种形式的动作设置为"excel.php"。然后它应该工作。希望对你有帮助。

编辑:在最后一秒看到了第二个表格。在这种情况下,您只需将 "to" 或 "from" 的输入转化为第二种形式。

您可以在单击按钮时更改 action 属性,如下所示:

$(function() { 
    $( ".actionable" ).click( function() {
        $('#myForm').attr('action', $(this).data("action"));
        $('#myForm').submit();
    });
});

并为您的按钮设置下一个 data-* 属性:

<form name="form" id="myForm" method="post">
    <input type="submit" class="actionable" value="Viewchart" data-action="foo.php"/>
    <input type="submit" class="actionable" value="Excel" data-action="excel.php"/>
</form>

你可以看到它是如何工作的here


相关链接:


Clarification for OP:

The $( function() {} ); block —equivalent to $(document).ready( function() {} );— specify a function to execute when the DOM is fully loaded; you should put inside all your code which interact with the elements of the DOM.

可以通过下一个脚本按照您的方式完成,并且在第二个表单声明中稍作更改

对于第二种形式你应该设置 id:

<form id="form2" action="excel.php" method="post">

你应该添加下一个脚本:

$("#form2").submit( function(eventObj){
$(this).append('<input type="hidden" name="from" value="'+$("#from").val()+'" /> ');  
$(this).append('<input type="hidden" name="to" value="'+$("#to").val()+'" /> ');               
return true;
});