cocos2d-js: How to load a JSON file

前端 未结 2 683
谎友^
谎友^ 2021-01-23 02:48

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         


        
相关标签:
2条回答
  • 2021-01-23 03:44

    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.

    0 讨论(0)
  • 2021-01-23 03:50

    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;           
        }
    });
    
    0 讨论(0)
提交回复
热议问题