Re-populate complex javascript objects from JSON
Say I have a web form that consists of a input text field, an Add button, and a Submit button. A user can add text to a div by typing some input and clicking Add, which will dynamically (using javascript) append the div with whatever they typed. Also during Add, I'm storing the text in a javascript object. After adding one or more items, the user then clicks Submit to send the data in the javascript object to the server to be saved. The data is serialized to a JSON string and sent to the server.
The problem I'm having is when, say, Refresh is hit while adding entries. I want the currently added entries to remain not only displayed on the page, but also in the javascript object.
What I have so far is that, after each Add, I use AJAX to send the current list to the server and save it as session data. What's the best way to get the data开发者_如何学JAVA from my session back into the client-side javascript object?
The best thing I can think of is to embed the JSON string back into the page and then use client-side javascript to re-populate the javascript object. That will work, but if the amount of data gets very large, I anticipate that the client-side javascript processing will be slow.
(Note that in my actual situation, my javascript object is a lot more complicated than this. It has functions where I've implemented inheritance and have prototyped "get" and "set" methods and such to dynamically build a somewhat complex set of objects. In other words, I cannot just overwrite my object by using eval(JSON).)
EDIT: Please note that it's not just Refresh where this comes into play. Previously submitted datasets can be edited, at which time I will need to repopulate the client-side javascript object which server-side data.
This is quite a broad question, and so it there may not be a unique answer to the problem. Let me just comment it then.
My first reaction (if I was the lead of the project) would be: "Don’t worry about the refresh button". I don’t think anybody reasonably expects the refresh button to preserve any state. That’s why it is called refresh. It has behaved this way since the beginning of the web, and so I don’t think it’s necessary to fight it. Yes, today it’s maybe unfortunate that it is still here and that it behaves like it does, and I’m sure it would not be here if the web was re-invented today.
But if you really for some reason need to preserve the state, I think what you are doing it’s a good solution. In case you are addressing modern browsers (IE8+, Firefox 2+, Safari 3+ etc.), I would also maybe recommend to consider the DOM storage. It would be perhaps more elegant – no server session required.
Here is another (random) comment. How serious is it when the user loses the state if she hits the refresh button? What if you hook on the window.onunload event and warn the user that there she may potentially lose some data? Would it be enough?
精彩评论