You could preserve web application state w开发者_运维问答ith 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.
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 an 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).
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!
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.
精彩评论