cocos2d-js: How to load a JSON file

旧巷老猫 提交于 2019-12-02 03:06:44

问题


How can I load a JSON file from the local filesystem into a javascript object?

Something similar to jQuery:

$.getJSON( "ajax/test.json", function( data ) {
    // data contains javascript object
}); 

回答1:


As answered in the official forums, you can make a call to cc.loader.loadJson:

cc.loader.loadJson("res/example.json", function(error, data){
    cc.log(data); //data is the json object
});

The function that you pass as parameter will be called back when the file finishes loading.




回答2:


Researching this I found following (not complete) solution:

var loadJSON = function(url, cb) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState==3 && xhr.status==200) {
            cb(null,JSON.parse(xhr.responseText));
        }
    }
    xhr.open("GET", url, true);
    xhr.send(null);
};

// read json file with words
loadJSON("res/words/dewords.words.json", function(err, text) {
    if( !err ) {
        muprisLayer.words = text;           
    }
});


来源:https://stackoverflow.com/questions/24359297/cocos2d-js-how-to-load-a-json-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!