Pregunta

I want to save some json data in a cookie and retrieve it in a different page with jquery cookie Here is how i get the data and store it.

        $.ajax({
            type: "POST",
            url: "V2_Loader.aspx/GetMenuData",
            data: "{id:" + id + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
            menus = response.d;
            $.cookie('menu-data', menus);
          }
     }

In a different page I try to retrieve it like this.

 menus = JSON.parse($.cookie("menu-data"));

but I get "JavaScript runtime error: Invalid character" I've tried turning on the json flag $.cookie.json = true; before storing it and when i try to print it out. like this

        var result;
            for (var i = 0; i < menus.length; i++) {
                result += menus[i].menuText + ', ';
            }
            alert(result);

I get this an array of undefined printed like here printed array

this is how my response looks like response

Any suggestions as to how i should be storing this and retrieving it?

¿Fue útil?

Solución 2

As an alternate solution to using a cookie, you could instead use sessionStorage in the browser.

$ajax({
  ...,
  success: function (response) {
    sessionStorage.setItem('menu-data', JSON.stringify(response.d));
  }
});

var menus = JSON.parse(sessionStorage.getItem('menu-data'));

Otros consejos

in $.cookie('menu-data', menus);, menus isn't json. You need to turn it into json.

$.cookie('menu-data', JSON.stringify(menus));

Due to the size of your json, you may be hitting a cookie length limitation.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top