Cocos2d-html5でデータ保存のためにXMLHttpRequestで処理を投げる
ゲームのデータ読み込み、データの保存を実装しています。
Javascriptの場合、直接MySQLなどのデータベースに接続してやり取りすることよりも、
APIを別途作成し、JSONを通じてやり取りすることが多いと思います。
例えば、データの読み込みの場合は
Cocos2d-xではCCHttpClientというmoduleが用意されていますが、html5版ではJavascriptなので普通にXMLHttpRequesやlocation.searchを使って行うようです。
簡単な例を記載しておきます。
//クエリパラメータからuser_idを引く var getQueryParams = function() { //get query param var option = []; var array = location.search.replace('?', '').split('&'); for (var i = 0; i < array.length; i++) { var tmp = array[i].split('='); option[tmp[0]] = tmp[1]; } cc.log("httpClient was called"); cc.log("user_id:" + option["user_id"]); }; //データを保存 var saveData = function(){ var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://localhost:8000/test.html', true); xhr.onload = function(e) { if (this.status == 200) { console.log(this.responseText); } }; xhr.send(); }; //データを読み込み var loadData = function(){ var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://localhost:8000/test.html', true); xhr.onload = function(e) { if (this.status == 200) { console.log(this.responseText); } }; xhr.send(); };
TwitterのAPIを用いた方法はCocos2d-html5でTwitterClientを3分で作る方法に記載しています。