tags:

views:

24

answers:

3

You could preserve web application state with JSON in URL like this:

  http://host/?state=[{id:1,selected=true},{id:2,selected=false}]

Is this preferable?

One motivation for doing something like this is if the user bookmarks the web page the web application state can be restored the next time the user visits the page.

A: 

You have to parse the JSON-String to get all the data back, which can be a little bit complex. But you can to it, if you dont want to use the query-string it self (maybe the structure is too compelex). But remember: the query string has a limited length!

alopix
A: 

It might be doable, but I think it's somewhat bad practice beacuse:

  • You are exposing a lot of technical details about your web app to the end users
  • Are you sure you're using safe JSON parsing? Otherwise your opening your app up to Javascript injection attacks.
  • Sooner or later you're bound to hit URL character encoding problems
  • Your URL's not very descriptive (see http://css-tricks.com/guidelines-for-uri-design/ )

My advice: create and ID for state bound to your JSON stored in a database (your URL's would look more along the lines of http://host/?state=123 with 123 pointing to some kind of database record (not that it makes the URL's very accessible either, but I still think it's better due to the other points cited).

Jacob Oscarson
knut
Ah, yes. Forgot that part. Maybe subjective but I think it's always better to POST your JSON than GET it. The above plugin looks like a sane choice for that (from a quick glance).
Jacob Oscarson
Just be careful with the library because "jQuery BBQ leverages the HTML5 hashchange event" and not all browsers support html5 yet.
Bojan Milenkoski
@Bojan that's right, and I've also had some unpleasant surprises with the onHashChange event (in Mobile WebKit if I don't remember wrong)
Jacob Oscarson
A: 

Your solution is fine. I have just few points for you.

One problem is the URL length. Different browsers have different limits. If you must do this and your URLs are approaching 2,000 characters in length than you might have problems. If your field names take up too much space, use a fixed field order instead. Leave out fields that doesn't need to be bookmarked. In extreme cases, consider using the gzip algorithm to compress your long URL. Then reencode that binary data in base64 using only characters that are legal in URLs. This comes with the cost of some CPU time when you unzip the URL again on the next visit.

An alternative is to store the state information in a file or a database. Then you can store only the identifier needed to look up that information again in the URL.

Bojan Milenkoski