jQuery cookie插件读取JSON对象 [英] jQuery cookie plugin read JSON Object
问题描述
我从PHP中将一些数据保存在assoc数组中.将一些Id放入数组中,然后进行json_encoded:
I am saving from PHP some data in assoc array. There are some Id's putted in an array and then json_encoded:
$ids = array(id => id, id2 => id2);
json_encode($ids);
store in the cookie ...
我正在将此插件用于jQuery: http://plugins.jquery.com/cookie/
I am using this plugin for jQuery: http://plugins.jquery.com/cookie/
这是字符串,存储在cookie中,值为:"xxx"
This is the string, what is stored in the cookie with value: "xxx"
%7B%2222504454%22%3A22504454%7D
path: "/"
domain: ".domain.com"
当我使用这个时:
var test = $.cookie( 'xxx');
我只收到Object
作为退货.
如何读取此数组?
推荐答案
JSON和JavaScript不支持" associative " Array
s 1 .它们的等效项是一个Object
. /p>
JSON and JavaScript don't support "associative" Array
s1. Their equivalent is an Object
.
<?php echo json_encode(array(id => 'foo', id2 => 'bar')); ?>
{ "id": "foo", "id2": "bar" }
他们的 Array
s 是索引从0
到length - 1
的已排序集合,可以从非关联数组生成.
Their Array
s are sorted collections with indexes from 0
to length - 1
and can be generated from a non-associative array.
<?php echo json_encode(array('foo', 'bar')); ?>
[ "foo", "bar" ]
注意:
-
对
- JavaScript
Array
进行实例化后,可以为其赋予非数字键,尽管此类键不会被计入length
中.
- JavaScript
Array
s can be given non-numeric keys after they've been instantiated, though such keys will not be counted in thelength
.
除此区别外:要将cookie
视为Object
或Array
,您需要使用 $.parseJSON()
.
Beyond that distinction: to treat the cookie
as either an Object
or Array
, you'll need to parse it with either JSON.parse()
or $.parseJSON()
.
var test = JSON.parse($.cookie('xxx'));
console.log(test.id);
console.log(test.id2);
这篇关于jQuery cookie插件读取JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!