2

如果 1 个表单使用“GET”方法而另一个使用“POST”,我如何提交位于同一页面上的 2 个表单。每个表单都有相同的操作并转到相同的下一页。需要帮忙。感谢大家的帮助。

我怎样才能得到下面这两种使用不同方法的表单,通过一个按钮提交?

<form method="POST" id="Form1" action="nextpage.html">

<input type="text" size="50" name="text_input">

<input type="submit" value="Submit">



<form method="GET" id="Form2" action="nextppage.html">

<input type="text" size="50" name="text_input">

<input type="submit" value="Submit">
4

5 回答 5

2

一种方法是为每个表单添加一个隐藏字段。例如,

<form action="action.php" method="get">
    <input type="hidden" name="id"  value="form1">
    Username: <input type="text" name="user">
    <input type="submit" value="Submit">
</form>

<form action="action.php" method="post">
    <input type="hidden" name="id" value="form2">
    Username: <input type="text" name="user">
    <input type="submit" value="Submit">
</form>

在您的脚本中,您只需检查一下 id 的值是多少。另一种方法是检查发送到服务器的请求是 post 还是 get。

于 2012-11-15T05:04:00.857 回答
1

递归地使用 AJAX 或将所有数据收集到一个表单中并提交该表单。

一个简单的表单提交将在第一个实例中重定向您的页面,而第二个实例中的数据将丢失。如果您可以完全控制服务器端,那么您可以只提交带有 POST 数据的表单(在我的示例中),并且您可以在提交之前将form2GET 应用于action属性。

我是说:

<form name="form1" id="form1" action="index.php" method="GET">
    <input type="text" name="foo" value="bar" />
    <input type="submit" value="Submit" />
</form>

<form name="form2" id="form2" action="index.php" method="POST">
    <input type="text" name="foo" value="bar" />
</form>

<script type="text/javascript">
    var f = document.getElementById('form1');
    f.onsubmit = function() {
        var t = f.getElementsByTagName('input'),
            l = t.length,
            i = 0,
            r = [];
        for (i = 0; i < l; i++) {
            if (!t[i].name) continue;
            r.push(t[i].name + '=' + encodeURIComponent(t[i].value));
        }
        var p = document.getElementById('form2');
        if (r.length) p.action += '?' + r.join('&');
        p.submit();
        return false;
    }
</script>

但是 AJAX 是一个更好、更优雅的解决方案,它可以在需要时使用新功能轻松扩展,所以我投票支持异步方式。

于 2012-11-15T05:14:31.707 回答
1

用一个按钮使用两个表单真的没有意义,它也不是有效的 html。

于 2012-11-15T05:16:15.727 回答
1

我会,使用您的 POST 表单提交,发布到页面,但不是发布到页面 nextpage.html,而是发布到类似“nextpage.html?var1=value&var2=value”之类的页面,
您将使用 javascript 的方式:

<form method="POST" id="Form1" action="nextpage.html">
<input type="text" size="50" name="text_input">
<input type="button" value="Submit" onclick="push();">
</form>

<form method="GET" id="Form2" action="nextpage.html">
<input type="text" size="50" name="text_input" id="name_input">
<input type="button" value="Submit" onclick="push();">
</form>

<script>
function push() {
    document.getElementById('Form1').action = "nextpage.html?text_input="+document.getElementById('name_input').value;
    document.getElementById('Form1').submit();
}
</script>

这应该可以工作,虽然很混乱,并且要小心有人将 ?、&、= 或其他非字母数字字符放入您要发送到 URL 栏的任何内容中。GET 和 POST 变量将被发送到页面。

于 2012-11-15T05:29:51.883 回答
0

您应该了解一下 HTTP 的工作原理。浏览器执行一个“请求”,通常是 GET 或 POST,响应正文被解析为 HTML 并显示在 Web 浏览器中。

同时发布两个表单没有任何意义,因为这会启动两个 HTTP 请求。哪一个应该用作浏览器中的新位置?

于 2012-11-15T05:02:25.263 回答