如何序列化一个JavaScript关联数组? [英] How to serialize a JavaScript associative array?

查看:118
本文介绍了如何序列化一个JavaScript关联数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要序列关联的JavaScript数组。
它的产品和数值的简单的形式,但只是建立阵列后,似乎是空的。

I need to serialize an associative JavaScript array. It's a simple form of products and a numeric values, but just after building the array seems empty.

在code是在这里: http://jsbin.com/usupi6/4/edit

The code is here: http://jsbin.com/usupi6/4/edit

推荐答案

在一般情况下,不要使用JS数组的关联数组。使用普通的对象:

In general, don't use JS arrays for "associative arrays". Use plain objects:

var array_products = {};

这就是为什么 $每个不起作用:jQuery的识别您传递的阵列的,并且只遍历数值属性。所有其他人将被忽略。

That is why $.each does not work: jQuery recognizes that you pass an array and is only iterating over numerical properties. 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.

更好的:

当你使用jQuery,您可以使用 jQuery.param [文件] 进行序列化。你只需要构建合适的输入数组:

As you use jQuery, you can use jQuery.param [docs] for serialization. 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);

没有必要实现自己的URI编码功能。

No need to implement your own URI encoding function.

DEMO

最佳:

如果你给输入字段适当名称

If you give the input fields a proper name:

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

您甚至可以使用 的.serialize() [文件] ,大大降低了code的量(我用的 一个相邻选择 [文件] ):

you can even make use of .serialize() [docs] and greatly reduce the amount of code (I use the next adjacent selector [docs]):

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

(将包括 0 值虽然)。

DEMO

这篇关于如何序列化一个JavaScript关联数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆