不包含按钮名称和值

不包含按钮名称和值

本文介绍了Ajax发布serialize()不包含按钮名称和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的$ .ajax()没有序列化按钮名称和值.

My $.ajax() is not serializing the button name and value.

我有一个非常简单的表格.它有一个按钮和一个文本框.

I have a very simple form. It has a button and a textbox.

<form action="/MyController/MyAction" data-ajax-method="post"
  data-ajax-mode="replace" data-ajax-target="#mypartial" id="myform"
  method="post">
        <button type="submit" class="positive" name="button" value="click1">
            <img src="/Id/Images/Icons/16/enabled/tick.png" title="click1">
            Click
        </button>
        <input id="txtBlah" name="txtBlah" type="text" value="hello">
    </div>
</form>

当我呼叫$(this).serialize()时,字符串中包含文本框,但按钮中不包含文本框.

When i call $(this).serialize(), the textbox is included in the string but not the button.

Debug.Log($(this).attr('id')); //== 'myform'
Debug.Log("data: " + $(this).serialize()); //== data: txtBlah=hello

我在研究过程中注意到,还有其他问题,主要原因是按钮上缺少名称元素.我有一个名字元素.

I noted during research that with other questions the main reason was a missing name element on the button. I have a name element.

我还尝试过制作一个非常简单的<input type="submit" name="mysubmit" />,它没有改变任何内容.

I have also tried making a very simple <input type="submit" name="mysubmit" /> which did not change anything.

我使用的解决方案

var buttonSubmit = (function (e)
{
    e.preventDefault();
    var form = $(this).closest('form');
    form.attr('data-button-name', $(this).attr('value'));
    form.closest('form').submit();
});

推荐答案

jQuery的serialize()非常明确地表示不对按钮进行编码或提交输入,因为它们不被视为成功的控件".这是因为serialize()方法无法知道单击了什么按钮(如果有!).

jQuery's serialize() is pretty explicit about NOT encoding buttons or submit inputs, because they aren't considered to be "successful controls". This is because the serialize() method has no way of knowing what button (if any!) was clicked.

我设法解决了这个问题,方法是单击按钮,序列化表格,然后将编码后的名称和单击按钮的值附加到结果上.

I managed to get around the problem by catching the button click, serializing the form, and then tacking on the encoded name and value of the clicked button to the result.

$("button.positive").click(function (evt) {
    evt.preventDefault();

    var button = $(evt.target);
    var result = button.parents('form').serialize()
        + '&'
        + encodeURI(button.attr('name'))
        + '='
        + encodeURI(button.attr('value'))
    ;

    console.log(result);
});

这篇关于Ajax发布serialize()不包含按钮名称和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 06:35