1

I have already searched from this question in SO. But none of the answers worked for me, so I am posting this once more in the hope to find an answer that works for me.

Is there a way to pass JS/JSON objects through URL? Suppose I have a JS Object like so:

var jObj = {"color":"red","shape":"square"}

Now suppose I want to pass it to a URL like so:

window.open("/process/jObj"); //here I want the var defined above to be passed

I tried various options like JSON.stringfy, encodeURIComponent, escape..but I am not able to pass it around. Any idea how this can be achieved in pure JS?

I would like to pass it so that in the next page (process.php) such that there I can get the values of jObj and use it for further processing. Basically I am looking for an option where I can pass the object to the effect of ?color=red&shape=square without having to squash and reformat the object too much

Undefined Variable
  • 4,196
  • 10
  • 40
  • 69

1 Answers1

2

Here is one thing you can do

var jObj = {"color":"red","shape":"square"}
var urlParam = []

for (var i in jObj){
   urlParam.push(encodeURI(i) + "=" + encodeURI(jObj[i]));
}

window.open("/process/?" + urlParam.join("&"));

this should produce your result

Ibu
  • 42,752
  • 13
  • 76
  • 103
  • 1
    You should use `encodeURI(i)` as well, since you don't know if the array keys will be URL-safe. – Kyle Sep 14 '12 at 20:18