簡體   English   中英

如何序列化JavaScript關聯數組?

[英]How to serialize a JavaScript associative array?

我需要序列化一個關聯的JavaScript數組。 它是一種簡單的產品形式和數值,但在構建數組之后似乎是空的。

代碼在這里: http//jsbin.com/usupi6/4/edit

通常,不要將JS數組用於“關聯數組”。 使用普通對象:

var array_products = {};

這就是為什么$.each不起作用的原因:jQuery認識到你傳遞一個數組並且只是迭代數值屬性。 所有其他人都將被忽略。

數組應該只包含帶數字鍵的條目。 您可以指定字符串鍵,但很多功能都不會將它們考慮在內。


更好:

在使用jQuery時,可以使用jQuery.param [docs]進行序列化。 您只需構造正確的輸入數組:

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編碼功能。

DEMO


最好:

如果為輸入字段指定正確的name

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

你甚至可以使用.serialize() [docs]並大大減少代碼量(我使用下一個相鄰的選擇器[docs] ):

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

(但它將包括0值)。

DEMO

您可以使用JSON庫 (或本機JSON對象,如果可用)將其序列化。

var serialised = JSON.stringify(obj);

JSON.stringify(object)

作為旁注,沒有關聯數組只有對象。

使用json-js支持IE6和IE7等傳統瀏覽器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM