I'm using CookieJar to read and write an Array of Objects to a cookie.
In my ClickButton function I do read the existing cookie and add to the Array of objects before I over write it again.
Here are the JSON string being saved:
[{"id":"3","value":"33333","text":"Bbbbb"},
[{"id":"3","value":"33333","text":"Bbbbb"},
[{"id":"5","value":"55555","text":"xxxxxx"}]]]
I want it really to be:
[{"id":"3","value":"33333","text":"Bbbbb"},
{"id":"3","value":"33333","text":"Bbbbb"},
{"id":"5","value":"55555","text":"xxxxxx"}]
Any ideas what I'm doing wrong here? I struggled with this for over a day now :)
Code:
<script type="text/javascript">
function Display() {
jar = new CookieJar({
expires: 3600, // seconds
path: '/'
});
var itemArray = jar.get("Items");
if (itemArray) {
tmpDiv.innerHTML += itemArray.toJSONString() + '<br/>';
for (var i = 0; i < itemArray.length; i++) {
tmpDiv.innerHTML += itemArray[i].item[0].value + '<br/>';
}
}
}
function Cl开发者_Go百科ickButton(id, value, text) {
jar = new CookieJar({
expires: 3600, // seconds
path: '/'
});
var tmpA = jar.get("Items");
var items = new Array;
items.push({ "id": id, "value": value, "text": text });
// If any existing values in the cookie, load and add to Array
if (tmpA != null)
items.push(tmpA);
tmpDiv.innerHTML += items.toJSONString() + "<br/>";
jar.put("Items", items);
}
</script>
Each time your button is clicked, you're creating a new array called items
, then adding the old array called tmpA
to it. Then, you stash items
, which now has a new child array inside it (representing the previous value, which itself was an array).
Instead of:
if (tmpA != null)
items.push(tmpA);
You should have:
if (tmpA != null)
items = items.concat(tmpA); // this will merge the two arrays
精彩评论