是否可以像这样嵌套html表单

<form name="mainForm">
  <form name="subForm">
  </form>
</form>

两种形式都适用吗?我的朋友有这个问题,subForm的一部分工作,而另一部分不工作。


当前回答

另一种解决这个问题的方法是,如果你使用一些服务器端脚本语言,允许你操纵发布的数据,就是这样声明你的html表单:

<form>
<input name="a_name"/>
<input name="a_second_name"/>
<input name="subform[another_name]"/>
<input name="subform[another_second_name]"/>
</form>

如果你打印发布的数据(我将在这里使用PHP),你会得到一个这样的数组:

//print_r($_POST) will output :
    array(
    'a_name' => 'a_name_value',
    'a_second_name' => 'a_second_name_value',
    'subform' => array(
      'another_name' => 'a_name_value',
      'another_second_name' => 'another_second_name_value',
      ),
    );

然后你可以这样做:

$my_sub_form_data = $_POST['subform'];
unset($_POST['subform']);

你的$_POST现在只有你的“主表单”数据,你的子表单数据存储在你可以随意操作的另一个变量中。

希望这能有所帮助!

其他回答

即使您可以让它在一个浏览器中工作,也不能保证它在所有浏览器中都能正常工作。所以虽然你可能能让它在某些时候工作,但你肯定不能让它在所有时候都工作。

第二个表单将被忽略,参见WebKit的代码片段:

bool HTMLParser::formCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
    // Only create a new form if we're not already inside one.
    // This is consistent with other browsers' behavior.
    if (!m_currentFormElement) {
        m_currentFormElement = new HTMLFormElement(formTag, m_document);
        result = m_currentFormElement;
        pCloserCreateErrorCheck(t, result);
    }
    return false;
}

今天,我也遇到了同样的问题,为了解决这个问题我增加了一个用户控件和 在这个控件上,我使用这个代码

<div class="divformTagEx">

</div>

<asp:Literal runat="server" ID="litFormTag" Visible="false">
'<div> <form  style="margin-bottom: 3;" action="http://login.php" method="post" name="testformtag"></form> </div>'</asp:Literal>

并在页面的PreRenderComplete事件中调用此方法

private void InitializeJavaScript()
{
        var script = new StringBuilder();
        script.Append("$(document).ready(function () {");
        script.Append("$('.divformTagEx').append( ");
        script.Append(litFormTag.Text);
        script.Append(" )");
        script.Append(" });");
        ScriptManager.RegisterStartupScript(this, GetType(), "nestedFormTagEx", script.ToString(), true);
    }

我相信这会有帮助。

一个简单的解决方法是使用iframe来保存“嵌套”表单。 从视觉上看,表单是嵌套的,但在代码方面,它在一个单独的html文件中。

不,你不能有嵌套的表单。相反,您可以打开一个包含表单的Modal并执行Ajax表单提交。