[英]how to serialize associative array with javascript save it in cookie and then read it with php?
[英]How to serialize a JavaScript associative array?
通常,不要將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編碼功能。
最好:
如果為輸入字段指定正確的name
:
<input name="sky_blue" class="percent_product" type="text" value="20" />
你甚至可以使用.serialize()
[docs]並大大減少代碼量(我使用下一個相鄰的選擇器[docs] ):
var serialized_products = $('.check_product:checked + input').serialize();
(但它將包括0
值)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.