简体   繁体   English

如何序列化JavaScript关联数组?

[英]How to serialize a JavaScript associative array?

I need to serialize an associative JavaScript array. 我需要序列化一个关联的JavaScript数组。 It's a simple form of products and a numeric values, but just after building the array seems empty. 它是一种简单的产品形式和数值,但在构建数组之后似乎是空的。

The code is here: http://jsbin.com/usupi6/4/edit 代码在这里: http//jsbin.com/usupi6/4/edit

In general, don't use JS arrays for "associative arrays". 通常,不要将JS数组用于“关联数组”。 Use plain objects: 使用普通对象:

var array_products = {};

That is why $.each does not work: jQuery recognizes that you pass an array and is only iterating over numerical properties. 这就是为什么$.each不起作用的原因:jQuery认识到你传递一个数组并且只是迭代数值属性。 All others will be ignored. 所有其他人都将被忽略。

An array is supposed to have only entries with numerical keys. 数组应该只包含带数字键的条目。 You can assign string keys, but a lot of functions will not take them into account. 您可以指定字符串键,但很多功能都不会将它们考虑在内。


Better: 更好:

As you use jQuery, you can use jQuery.param [docs] for serialization. 在使用jQuery时,可以使用jQuery.param [docs]进行序列化。 You just have to construct the proper input array: 您只需构造正确的输入数组:

var array_products = []; // now we need an array again
$( '.check_product:checked' ).each(function( i, obj ) {
    // index and value
    var num = $(obj).next().val();
    var label = $(obj).next().next().attr( 'data-label' );
    // build array
    if( ( num > 0 ) && ( typeof num !== undefined ) ) {
        array_products.push({name: label, value: num});
    }      
});

var serialized_products = $.param(array_products);

No need to implement your own URI encoding function. 无需实现自己的URI编码功能。

DEMO DEMO


Best: 最好:

If you give the input fields a proper name : 如果为输入字段指定正确的name

<input name="sky_blue" class="percent_product" type="text" value="20" />

you can even make use of .serialize() [docs] and greatly reduce the amount of code (I use the next adjacent selector [docs] ): 你甚至可以使用.serialize() [docs]并大大减少代码量(我使用下一个相邻的选择器[docs] ):

var serialized_products = $('.check_product:checked + input').serialize();

(it will include 0 values though). (但它将包括0值)。

DEMO DEMO

您可以使用JSON库 (或本机JSON对象,如果可用)将其序列化。

var serialised = JSON.stringify(obj);

JSON.stringify(object)

As a sidenote there are no associative arrays there are only objects. 作为旁注,没有关联数组只有对象。

Use json-js to support legacy browsers like IE6 and IE7 使用json-js支持IE6和IE7等传统浏览器

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

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