11

how to pass a js object through url

i have a js object

var info = {
    status: 1 ,
    time: "10:00:00-12:00:00" ,
    weekdays: {
      "monday",
      "tuesday"
    }
};

i don't want to use serialize, i want something like "localhost/jstest/#test?info"

Is there any way i can achieve this

3
  • will your object have second level?for example object{ p : "value" , p2 : value , p3 : {pi1 : value , pi2 : value} } Commented Jun 16, 2012 at 11:29
  • but weekdays looks more like an array than object. Commented Jun 16, 2012 at 11:39
  • My question is a duplicate of this one. stackoverflow.com/questions/15399749/… Commented Mar 15, 2013 at 4:34

3 Answers 3

9

You are going to have to serialize it one way or another. You could do it in the way you suggest by storing a JSON string representing your object in e.g. sessionStorage, and passing the name of the key:

sessionStorage.setItem("info", JSON.stringify(info));
window.location("localhost/jstest/#test?info");

You can then access the data stored in that key:

var info = JSON.parse(sessionStorage.getItem("info"));
Sign up to request clarification or add additional context in comments.

3 Comments

It won't work in IE below 8. But if you care about older browsers you could use a cookie instead, or use a web storage polyfill.
i will have to care about older browsers
Then use a cookie or the polyfill that I linked to.
1

You can create your own querystring with the hashtag, then get the data from the url/hashtag in your code to retrieve the data.

like this:

localhost/jstest/#info!status=1!time=10:00:00-12:00:00!weekdays=monday,tuesday

Then you can find more help on how to read the hashtag data here: Working with single page websites and maintaining state using a URL hash and jQuery

Comments

1

This is my solution. Here you convert your object to JSON first, after making that string safe with base64 encoding for use in URL. Note this uses an additional plugin jquery.base64.js for working with base64. You can use your own library.

function packer(o){
    var str = JSON.stringify(a);
    var mess = $.base64.encode(str);
    return mess.replace(/\+/g,'-').replace(/\//g,'_').replace(/=/g,',');
}
function unpacker(str){
    var mess  = str.replace(/-/g,'+').replace(/_/g,'/').replace(/,/g,'=');
    mess = $.base64.decode(mess);
    return JSON.parse(mess);
}

1 Comment

javascript version function packer(o){ var str = JSON.stringify(o); var mess = btoa(str); return mess.replace(/\+/g,'-').replace(/\//g,'_').replace(/=/g,','); } function unpacker(str){ var mess = str.replace(/-/g,'+').replace(/_/g,'/').replace(/,/g,'='); mess = atob(mess); return JSON.parse(mess); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.