Imagine that HTML page is a game surface (see picture).
User can have n number of boards (blue divs) on his page. Each board can be moved, re-sized, relabeled, created new and removed.Inside each board there are m number of figures (purple divs). Each of these user can move inside the board or to another board, re-size, change color and label, delete, add new.
The goal of the game is not important, but let's say it is to rearrange figures in a certain way so that they disappear.But the goal of the programmer is to save the whole game surface in the database for every user of the site, and to load it later when he returns.
So, how do I go about data exchange between client and the database?
Here's how I think it can be, but maybe there is a better way.
In the database I think of creating tables users, boards and figures.Then I can SELECT all that belongs to a user and create his HTML page (surface).
But then, user will be able to chang开发者_如何学Ce all of those properties of boards and figures and I don't know how to track those changes and how to save them back to the database. Is this a situation where JSON should be used?
Yes, if Javascript is an option, then basically you should generate a document (xml or json or plain text, doesn't really matter that much, though json is probably easiest if you're using javascript) that describes the serialized state of the board.
You can then track all changes client-side in a javascript object, and have javascript serialize that as a string that you then transfer to the server using XHR.
I would say that generally, in this scenario, you're best off with each object being a DOM element of some kind (div, span, whatever), because that way the browser can do all the work for you on figuring out positions and such, just absolutely position it all and work from there.
I'm assuming this is mostly going on with javascript when they're playing and that you already know how to do that. Well, each figure has propertes, like this: -board (the one it's in) -id -label -width -height -color -x position (relative to board) -y position (relative to board)
So each of those properties will be held in a javascript variable or array while playing. Likewise, the boards also have properties: -id -label -width -height -color -x position (relative to page) -y position (relative to page) So you will hold these in javascript variables as well.
When you save you just need to pass all of those variables over to the server. So make your XHR with your JSON string. Once your server receives the request you translate the JSON back into variables you can stick in the database. The way you're planning your database sounds appropriate.
To restore you would just SELECT the appropriate info for that user and (either with a normal page load or XHR) and use your javascript that moves everything around to create and position the objects where they need to go.
精彩评论