Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to transport a javascript object via query string

I have a javascript object that I need to be able to pass to a web service via query string.

Say for example:

<script type="text/javascript">
var test = new Object();
test.date = new Date();
test.str = "hello world!";
test.list = new Array();
test.list.push('a');
test.list.push('b');
test.list.push('c');
</script>

Is there a way that I can serialize that object as JSON and then compress/encode it in some way that can be passed into a url's query string?

like:

var destination = 'http://mywebservice?'+encode(serialize(test));
$.get(destination, function(e)) { ... }

Thanks in advance

like image 230
john Avatar asked Dec 16 '22 16:12

john


1 Answers

You want Douglas Crockford's json2.js: https://github.com/douglascrockford/JSON-js

var test = new Object();
test.date = new Date();
test.str = "hello world!";

var dest = 'http://mywebservice?'+encodeURIComponent( JSON.stringify(test) );

(oh, and don't use escape(), it's deprecated. Always use encodeURIComponent() instead)

But why not use a (session) cookie instead? Using the URI to pass data can be a major problem for SEO, for bookmarks, for links, etc.

like image 102
Jens Roland Avatar answered Dec 19 '22 06:12

Jens Roland