Loading local JSON file

前端 未结 23 1630
悲哀的现实
悲哀的现实 2020-11-22 01:28

I\'m trying to load a local JSON file but it won\'t work. Here is my JavaScript code (using jQuery):

var json = $.getJSON("test.json");
var data = e         


        
23条回答
  •  醉酒成梦
    2020-11-22 01:58

    You can put your json in a javascript file. This can be loaded locally (even in Chrome) using jQuery's getScript() function.

    map-01.js file:

    var json = '{"layers":6, "worldWidth":500, "worldHeight":400}'
    

    main.js

    $.getScript('map-01.js')
        .done(function (script, textStatus) {
            var map = JSON.parse(json); //json is declared in the js file
            console.log("world width: " + map.worldWidth);
            drawMap(map);
        })
        .fail(function (jqxhr, settings, exception) {
            console.log("error loading map: " + exception);
        });
    

    output:

    world width: 500
    

    Notice that the json variable is declared and assigned in the js file.

提交回复
热议问题