【问题标题】:jQuery - how to get the value of an input of type submit when ajaxifying a formjQuery - 如何在ajaxifying表单时获取提交类型的输入值
【发布时间】:2011-06-23 13:54:03
【问题描述】:

假设我有以下代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd"
    >
<html lang="en">
<head>
    <title><!-- Insert your title here --></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function(){
            $('#form1').submit(function(){

                // Let's see the values
                alert($(this).serialize());

                $.post($(this).attr('action'), $(this).serialize(), function(data){

                    // Do something on callback

                });

                return false;
            })
        });

    </script>
</head>
<body>
    <form action="http://example.com/bla" method="POST" id="form1">
        <input type="hidden" name="ipt1" value="1"/>
        <input type="submit" name="sbt" value="2"/>
    </form>
</body>
</html>

当我序列化表单的值时,点击的输入类型的值不存在。 ajax 化表单时如何处理这种情况?

【问题讨论】:

    标签: javascript jquery html ajax dom


    【解决方案1】:

    这是设计使然。 .serialize() 方法不会序列化 submit 类型的输入。

    不幸的是,您拥有它的方式将无法访问事件的来源。最好的办法是连接所有提交,然后像这样附加源数据:

    $('input:submit').bind('click', function(){    
    
    var data = $("#form1").serialize();
    data += "&"+escape($(this).attr("name"))+"="+escape($(this).val());
    
    alert(data);
    $.post($('#form1').attr('action'), data, function(data) {
    //do something
    });
    
    return false;
    });
    

    【讨论】:

    • 有没有比处理提交类型的所有输入的所有点击以将其值附加到表单更好的方法?
    【解决方案2】:

    在非 ajax 表单中,提交按钮的值仅在被点击时随表单一起发送。所以如果你想用 ajax 模仿这种行为,你必须这样做:

    $("#submit_button").click(function() {
        var data = $("#my_form").serialize();
        data += data.length ? "&" : ""; // check if empty
        data += escape($(this).attr("name"))+"="+escape($(this).val());
        // ...
        return false;
    });
    

    这会将提交按钮的序列化数据附加到序列化的表单数据中。

    【讨论】:

    • 这种方法的问题是我的表单上有很多提交类型的输入。
    • 你的意思是,我写的代码只有一个提交按钮?它可以延长更多。
    • 是的,我已经对所有重要的输入进行了分类以识别它们。非常感谢!
    【解决方案3】:

    我正在使用以下解决方案:

    <input type="radio" name="action" value="action_1" style="display:none"></input>
    <button type="submit" onclick="this.previousElementSibling.checked=true" >Do Action 1</button>
    

    您对任意数量的选项(名称、值)重复此操作,并且只要您选择一个,表单就会提交。 确保页面在使用后重新加载。

    【讨论】:

      猜你喜欢
      • 2013-11-04
      • 1970-01-01
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      • 2018-06-07
      • 2013-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多