In javaScript, using jQuery library, I need to:
在javaScript中,使用jQuery库,我需要:
- Take an array of objects.
- 取一个对象数组。
- Stringify it.
- Stringify它。
- Save it as a cookie.
- 把它保存为cookie。
- On refresh -> Parse cookie and 'recreate' the array.
- 在refresh ->解析cookie并“重新创建”数组。
Using JSON is easy.
使用JSON是容易的。
// Write JSON Cookie
var foo = JSON.stringify(myValue);
writeCookie(foo);
// Read [Eat?] JSON Cookie
var foo = JSON.parse(readCookie("myArray"));
if(foo.length) {
myArray = foo;
}
(Note: writeCookie(); readCookie(); Are 2 functions I wrote based on the suggested cookie functions on quirksmode.org.)
(注意:writeCookie();readCookie();这是我基于quirksmode.org上的cookie功能编写的两个函数。
Now, my user base involves a lot of pre-IE8 browsers. (Which won't support these methods). So I want to turn to jQuery to plug in the holes. Parsing JSON is easy:
现在,我的用户群包括了很多ie8前的浏览器。(不支持这些方法)。所以我想求助于jQuery来填补漏洞。解析JSON很容易:
// Read JSON Cookie with jQuery
var foo = jQuery.parseJSON(readCookie("myArray"));
if(foo.length) {
myArray = foo;
}
My question is how do I write a JSON object to cookie using jQuery (Such that it will work for earlier versions of IE).
我的问题是如何使用jQuery将JSON对象写入到cookie中(这样它才能在IE的早期版本中工作)。
Thanks
谢谢
Update: Still confused why jQuery would offer a parseJSON function and not a writeJSON function?
更新:为什么jQuery会提供parseJSON函数而不是writeJSON函数?
3 个解决方案
#1
3
It's the native function JSON.stringify
; standard jQuery does not provide a compatibility wrapper around it, but browser compatibility is not bad (will work on IE >= 8 and everything else).
它是原生函数json。stringify;标准jQuery并没有提供兼容包装,但是浏览器的兼容性还不错(适用于IE >= 8等)。
#2
1
You can use JSON2 library https://github.com/douglascrockford/JSON-js for compatibility with older browsers.
您可以使用JSON2库https://github.com/douglas / json -js来与旧的浏览器兼容。
#3
0
The best way is to include the polyfill for JSON object.
最好的方法是包含JSON对象的polyfill。
But if you insist create a method for serializing an object to JSON notation inside the jQuery namespace, you can do something like this:
但是,如果您坚持要在jQuery名称空间中创建一个方法,将对象序列化为JSON标记,那么您可以这样做:
用jQuery序列化JSON
#1
3
It's the native function JSON.stringify
; standard jQuery does not provide a compatibility wrapper around it, but browser compatibility is not bad (will work on IE >= 8 and everything else).
它是原生函数json。stringify;标准jQuery并没有提供兼容包装,但是浏览器的兼容性还不错(适用于IE >= 8等)。
#2
1
You can use JSON2 library https://github.com/douglascrockford/JSON-js for compatibility with older browsers.
您可以使用JSON2库https://github.com/douglas / json -js来与旧的浏览器兼容。
#3
0
The best way is to include the polyfill for JSON object.
最好的方法是包含JSON对象的polyfill。
But if you insist create a method for serializing an object to JSON notation inside the jQuery namespace, you can do something like this:
但是,如果您坚持要在jQuery名称空间中创建一个方法,将对象序列化为JSON标记,那么您可以这样做:
用jQuery序列化JSON