jQuery SerializeArray 不包含单击的提交按钮

发布于 2024-09-28 23:14:59 字数 1507 浏览 3 评论 0 原文

我有一个有两个按钮的表单。一个用于保存记录,另一个用于取消保存过程。我正在使用 rails.js (对于那些不了解的人来说是一个常见的 AJAX/jQuery 插件) javascript 文件,它与 jQuery 一起使用以实现不显眼的 javascript/ajax来电。当我通过 ajax 发送表单数据时,我希望将我单击的按钮的名称和值与其余数据一起提交,以便我可以根据单击的按钮来决定要做什么。

rails.js 文件中的方法使用 .serializeArray() 将表单数据发送到服务器。问题是这不包括我单击的按钮的名称/值对。 jQuery 的网站声明他们是故意这样做的(尽管我认为他们应该这样做):

.serializeArray() 方法使用 成功控制以确定应包含哪些元素;特别是元素不能被禁用并且必须包含名称属性。由于未使用按钮提交表单,因此不会序列化提交按钮值。”

他们如何假设表单不是使用按钮提交的?我认为这是没有意义的,也是一个错误的假设。

根据 W3C 规则,为提交表单而激活的按钮被视为成功控件

既然 jQuery 的开发人员决定故意这样做,我是否可以假设还有另一种方法在序列化中排除激活的按钮?

编辑:这是我的表单的快速示例......

<!DOCTYPE html5>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $('#form').submit(function(e) {
      // put your breakpoint here to look at e
      var x = 0;
    });
  });
</script>
</head>
<body>
  <form id="form">
    <input name="name" type="text"><br/>
    <input name="commit" type="submit" value="Save"/>
    <input name="commit" type="submit" value="Cancel"/>
  </form>
</body>

I have a form that has two buttons. One for saving a record and the other for cancelling the save procedure. I am using the rails.js (a common AJAX/jQuery plug-in for those of you not in the know) javascript file that works with jQuery for unobtrusive javascript/ajax calls. When I send the form data over ajax, I want the name and value of the button I clicked to be submitted with the rest of the data so that I can make a decision on what to do based on which button was clicked.

The method in the rails.js file uses .serializeArray() for sending form data to the server. The problem is that this doesn't include the name/value pair of the button I've clicked. jQuery's website states that they do this on purpose (eventhough its my opinion that they should):

"The .serializeArray() method uses the standard W3C rules for successful controls to determine which elements it should include; in particular the element cannot be disabled and must contain a name attribute. No submit button value is serialized since the form was not submitted using a button."

How can they assume that a form WASN'T submitted using a button? This makes no sense and a wrong assumption I believe.

Under the W3C rules the button which was activated for the submission of a form is considered a successful control.

Since the developers of jQuery have decided to do this on purpose, can I assume that there is another method that DOESN'T exclude the activated button in a serialization?

EDIT: Here is quick example of what my form might look like...

<!DOCTYPE html5>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $('#form').submit(function(e) {
      // put your breakpoint here to look at e
      var x = 0;
    });
  });
</script>
</head>
<body>
  <form id="form">
    <input name="name" type="text"><br/>
    <input name="commit" type="submit" value="Save"/>
    <input name="commit" type="submit" value="Cancel"/>
  </form>
</body>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

勿忘初心 2024-10-05 23:14:59

是否有另一种方法排除序列化中激活的按钮?

不存在,该行为基于

submit 事件,而不是按钮的 >,例如按 Enter 或调用 .submit() 在 JavaScript 中。您在这里混合了两个概念, .serialize() 或 < a href="http://api.jquery.com/serializeArray/" rel="noreferrer">.serializeArray() 可能有也可能没有任何东西 与按钮单击有关 - 这只是一个单独的事件,它们没有连接。这些方法的级别更高:您可以出于任何原因随时序列化表单(或其子集)。

但是,您可以添加提交名称/值对,就像从该按钮提交的普通表单一样,如果您从按钮提交,例如:

$("#mySubmit").click(function() {
  var formData = $(this).closest('form').serializeArray();
  formData.push({ name: this.name, value: this.value });
  //now use formData, it includes the submit button
});

Is [there] another method that DOESN'T exclude the activated button in a serialization?

There is not, the behavior is based on the submit event of the <form>, not of a button, e.g. hitting enter or calling .submit() in JavaScript. You're mixing 2 concepts here, a .serialize() or .serializeArray() may or may not have anything to do with a button click - it's just a separate event altogether, they're not connected. These methods are at a higher level than that: you can serialize a form (or a subset of it) at any time for any reason.

You can however add the submit name/value pair like a normal form submitting from that button would, if you're submitting from a button for example:

$("#mySubmit").click(function() {
  var formData = $(this).closest('form').serializeArray();
  formData.push({ name: this.name, value: this.value });
  //now use formData, it includes the submit button
});
请恋爱 2024-10-05 23:14:59

这是解决这个问题的一个相当巧妙的方法:

<form>
    <input type="hidden" name="stuff" value="">
    <button type="submit" onclick="this.form.stuff.value=this.value" value="reset">reset</button>
    <button type="submit" onclick="this.form.stuff.value=this.value" value="delete">delete</button>
</form>

Here's a fairly neat way to solve this:

<form>
    <input type="hidden" name="stuff" value="">
    <button type="submit" onclick="this.form.stuff.value=this.value" value="reset">reset</button>
    <button type="submit" onclick="this.form.stuff.value=this.value" value="delete">delete</button>
</form>
如若梦似彩虹 2024-10-05 23:14:59

我使用以下代码片段,基本上添加了一个具有相同名称的隐藏元素

 var form = $("form");
 $(":submit",form).click(function(){
            if($(this).attr('name')) {
                $(form).append(
                    $("<input type='hidden'>").attr( { 
                        name: $(this).attr('name'), 
                        value: $(this).attr('value') })
                );
            }
        });

 $(form).submit(function(){
     console.log($(this).serializeArray());
 });

I use the following snippet, basically adds a hidden element with same name

 var form = $("form");
 $(":submit",form).click(function(){
            if($(this).attr('name')) {
                $(form).append(
                    $("<input type='hidden'>").attr( { 
                        name: $(this).attr('name'), 
                        value: $(this).attr('value') })
                );
            }
        });

 $(form).submit(function(){
     console.log($(this).serializeArray());
 });
风流物 2024-10-05 23:14:59

该解决方案是“通用的”,因为它将处理您的所有输入提交,并在提交时将每个输入作为表单变量传递。

$(document).ready(function(){
    $('input:submit').each(function(){
        $(this).click(function(){
            var formData = $(this).closest('form').serializeArray();
            formData.push({ name: $(this).attr('name'), value: $(this).val() });
        });
    });
});

This solution is 'universal' as in it will handle all your input submits, passing each as a form variable on submission.

$(document).ready(function(){
    $('input:submit').each(function(){
        $(this).click(function(){
            var formData = $(this).closest('form').serializeArray();
            formData.push({ name: $(this).attr('name'), value: $(this).val() });
        });
    });
});
上课铃就是安魂曲 2024-10-05 23:14:59
    var form = button.closest('form');
    var serialize = form.serialize();

    if (button.attr('name') !== undefined) {
        serialize += '&'+button.attr('name')+'=';
    }
    var form = button.closest('form');
    var serialize = form.serialize();

    if (button.attr('name') !== undefined) {
        serialize += '&'+button.attr('name')+'=';
    }
半寸时光 2024-10-05 23:14:59

有点晚了,但如果您不想将事件绑定到表单上的每个按钮,您可以包含以下内容:

$form.on('submit', function (e) {

    let formData = $(this).serializeArray();

    if (
        e.originalEvent
        && undefined !== e.originalEvent.submitter
        && undefined !== e.originalEvent.submitter.name
        && typeof e.originalEvent.submitter.name == "string"
        && e.originalEvent.submitter.name.length >= 1
        && undefined !== e.originalEvent.submitter.value
    ) {
        formData.push({
            name: e.originalEvent.submitter.name,
            value: e.originalEvent.submitter.value,
        });
    }

    // ...

});

表单上的任何提交按钮,其字符串名称至少为 1 个字符长,并且将包含定义的值在 formData 对象数组中。

A bit late, but if you don't want to bind an event to each button on your form, you can include this:

$form.on('submit', function (e) {

    let formData = $(this).serializeArray();

    if (
        e.originalEvent
        && undefined !== e.originalEvent.submitter
        && undefined !== e.originalEvent.submitter.name
        && typeof e.originalEvent.submitter.name == "string"
        && e.originalEvent.submitter.name.length >= 1
        && undefined !== e.originalEvent.submitter.value
    ) {
        formData.push({
            name: e.originalEvent.submitter.name,
            value: e.originalEvent.submitter.value,
        });
    }

    // ...

});

Any submit button on your form that has a string name at least 1 character long and a defined value will be included in the formData array of objects.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文