When playing the game often need a function is the storage of data, such as the game highest score, the number of gold coins, the number of items, etc., cocos2d-html5 using html5, therefore, the html5 data storage method is available to the engine;
Html5 local data storage uses js to operate data. html5 provides two methods for data storage:
SessionStorage-only retain data for this session
LocalStorage-keep data for a long time
This sessionStorage is only available when the browser opens a session. It is not tested in the game. Its usage is the same as that of localStorage, but it only differs in the data storage time;
The localStorage method has no time limit on the retained data. Unless you manually clean up the data, it is also a common method in the game;
The most common methods for data storage are getItem ('',''); and setItem;
It can be seen that the local data storage method is very simple, that is, simply setting the key value pair, and obtaining the saved value based on the key );
Another thing to note is that html5 local data storage can only store string data. Whatever you save, it will be automatically converted to a string. Therefore, if you want to save other types of data, remember to convert data,
Here I will write an example to save and read json data:
// This is the json data dollNum = {Aries: 0, Taurus: 0, Gemini: 0, Cancer: 0, Leo: 0, Virgo: 0, Libra: 0, Scorpius: 0, Sagittarius: 0, Capricornus: 0, Aquarius: 0, Pisces: 0};/*** Number of Doll files to be saved, JSON is required. stringify (); method converts JSON to a string */function saveDollNum () {var tempDollNum = JSON. stringify (dollNum); sys. localStorage. setItem ("dollNum", tempDollNum);}/*** load the number of Doll and keys, and then use JSON. parse (); method converts string to JSON */function loadDollNum () {var tempDollNum = sys. localStorage. getItem ("dollNum"); if (tempDollNum = null | tempDollNum = "") {saveDollNum (); cc. log ("default dollNum" + dollNum);} else {tempDollNum = sys. localStorage. getItem ("dollNum"); cc. log ("get dollNum" + tempDollNum);} // convert the string to json tempDollNum = JSON. parse (tempDollNum );}
In this way, you can save multiple data at a time and perform operations conveniently.
OK data storage introduction, more exciting in my personal original blog site: Melove I love http://www.melove.net