jQuery jQuery表单序列化 - 空字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2591354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:50:50  来源:igfitidea点击:

jQuery form serialize - empty string

jqueryhtml

提问by user137348

My html:

我的html:

 <script type="text/javascript">

    $(function() {

        $("#bt1").click(function() {

            var f = $("#form1");
            var formData = f.serialize();

            alert(formData);
        });

    }); 
</script> 

 <div id="div1">
      <form id="form1" action="/Home/Test1" method="post" name="down">
        <div id="div2">
            <input id="input1" type="text" value="2" />
        </div>    
      </form>
  </div>

 <input type="submit" id="bt1" />

When I fire up the click event, formData is empty. I'm using jQuery 1.4.2.

当我启动 click 事件时,formData 为空。我正在使用 jQuery 1.4.2。

回答by Felix Kling

You have to give the inputelement a name. E.g.:

您必须为input元素命名。例如:

<form id="form1" action="/Home/Test1" method="post" name="down">
    <div id="div2">
        <input id="input1" type="text" value="2" name="foo"/>
    </div>    
</form>

will give you in the alert box foo=2.

会给你在警报框中foo=2

.serialize()takes the name and the value of the form fields and creates a string like name1=value1&name2=value2. Without a name it cannot create such a string.

.serialize()获取表单字段的名称和值并创建一个字符串,如name1=value1&name2=value2. 没有名称,它无法创建这样的字符串。

Note that nameis something different than id. Your form also would have not worked if you used it in the "normal" way. Every form field needs a name.

请注意,name这与id. 如果您以“正常”方式使用它,您的表单也将无法使用。每个表单域都需要一个名称。

回答by Madbreaks

Although it doesn't apply to this particular example, the same behavior occurs if one or more form inputs is disabled. Those inputs will not show up in the serialized string. In my case, all form inputs had values but were disabled, resulting in an empty string being returned.

尽管它不适用于此特定示例,但如果一个或多个表单输入是disabled. 这些输入不会显示在序列化字符串中。就我而言,所有表单输入都有值但被禁用,导致返回空字符串。

回答by Victor

There is no nameattribute in the input... that may be a problem for serialize.

name输入中没有属性......这可能是序列化的问题。

<input id="input1" type="text" value="2" name="input1" />

回答by VahidN

Also make sure there are no 2 elements with the same id on the page.

还要确保页面上没有 2 个具有相同 id 的元素。