简体   繁体   English

将项添加到数组,然后序列化()javascript

[英]Add items to an array and then serialize() javascript

I'm trying to add an item to an array in javascript and then serialize the array. 我正在尝试在javascript中将项添加到数组中,然后序列化数组。 However, it doesn't seem to be working. 但是,它似乎没有起作用。

Please see below code, what am I doing wrong? 请看下面的代码,我做错了什么?

var currentParent = $(this).closest('tr');
var items = $("input,select", currentParent);
items["_token"] = $('input[name=_token]').val();
var strData = items.serialize();

Method serialize needs to be applied to a whole form, not to specific items in array, if you want to serialize existing object or array you need to use param instead 方法serialize需要应用于整个表单,而不是应用于数组中的特定项,如果要序列化现有对象或数组,则需要使用param代替

http://api.jquery.com/jquery.param/ http://api.jquery.com/jquery.param/

As an example : 举个例子 :

<form action="">
   <input class="token" name="token" value="someValue" />
   <input class="someData" name="someData" />
</form>

<script>
    alert($('form').serialize()) // should show you someData=&token=someValue
</script>

https://jsfiddle.net/4cxa36vp/ https://jsfiddle.net/4cxa36vp/

... or ... ... 要么 ...

var options = {
    token : $('input.token').val(),
    someData : null
}

alert($.param(options)) // should give you the same

https://jsfiddle.net/0ec8axot/ https://jsfiddle.net/0ec8axot/

Also, make sure that your form fields have attribute name 另外,请确保您的表单字段具有属性name

Serialize form not working in jQuery 序列化不适用于jQuery的表单

Try the below javscript code snippet. 试试下面的javscript代码片段。 I have not tried but i think it might work: 我没试过,但我认为它可能会奏效:

var currentParent = $(this).closest('tr');
var items = $(currentParent).find("input, select");
items["_token"] = $('input[name=_token]').val();
var strData = items.serialize();

See the below fiddle link: https://jsfiddle.net/nanncngr/ 请参阅以下小提琴链接: https//jsfiddle.net/nanncngr/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM