我在一个表单中有两个提交按钮。我如何确定哪一个击中了服务器端?


当前回答

你可以像这样显示按钮:

<input type="submit" name="typeBtn" value="BUY">
<input type="submit" name="typeBtn" value="SELL">

然后在代码中,你可以使用:

if request.method == 'POST':
    #valUnits = request.POST.get('unitsInput','')
    #valPrice = request.POST.get('priceInput','')
    valType = request.POST.get('typeBtn','')

(valUnits和valPrice是我从表单中提取的其他一些值,用于演示)

其他回答

简单。你可以在不同的提交按钮上点击改变表单的动作。

在文档中试试这个。准备好:

$(".acceptOffer").click(function () {
    $("form").attr("action", "/Managers/SubdomainTransactions");
});

$(".declineOffer").click(function () {
    $("form").attr("action", "/Sales/SubdomainTransactions");
});

您还可以使用href属性并为每个按钮发送带有附加值的get。但那时就不需要填表格了

href="/SubmitForm?action=delete"
href="/SubmitForm?action=save"
<form>
    <input type="submit" value="Submit to a" formaction="/submit/a">
    <input type="submit" value="submit to b" formaction="/submit/b">    
</form>

在HTML5中,你可以在输入字段中使用formaction和formmethod属性

<form action="/addimage" method="POST">
<button>Add image</button>
<button formaction="/home" formmethod="get">Cancel</button>
<button formaction="/logout" formmethod="post">Logout</button>
</form>

处理多个提交按钮的最佳方法是在服务器脚本中使用切换案例

<form action="demo_form.php" method="get">

    Choose your favorite subject:

    <button name="subject" type="submit" value="html">HTML</button>
    <button name="subject" type="submit" value="css">CSS</button>
    <button name="subject" type="submit" value="javascript">JavaScript</button>
    <button name="subject" type="submit" value="jquery">jQuery</button>
</form>

服务器代码/服务器脚本-你提交表单的地方:

文件demo_form.php

<?php
    switch($_REQUEST['subject']) {

        case 'html': // Action for HTML here
                     break;

        case 'css': // Action for CSS here
                    break;

        case 'javascript': // Action for JavaScript here
                           break;

        case 'jquery': // Action for jQuery here
                       break;
    }
?>

来源:W3Schools.com