jQuery cookie插件读取JSON对象 [英] jQuery cookie plugin read JSON Object

查看:114
本文介绍了jQuery cookie插件读取JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从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" Arrays1. Their equivalent is an Object.

<?php echo json_encode(array(id => 'foo', id2 => 'bar')); ?>

{ "id": "foo", "id2": "bar" }

他们的 Array s 是索引从0length - 1的已排序集合,可以从非关联数组生成.

Their Arrays 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" ]

注意:

  1. JavaScript Array进行实例化后,可以为其赋予非数字键,尽管此类键不会被计入length中.
  1. JavaScript Arrays can be given non-numeric keys after they've been instantiated, though such keys will not be counted in the length.


除此区别外:要将cookie视为ObjectArray,您需要使用 $.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屋!

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