使用js文件访问本地JSON对象

时间:2017-05-24 05:35:20

标签: javascript jquery json ajax

我正在使用js文件来尝试访问本地JSON文件。但它没有用。即使我使用了正确的url,代码仍然无法从JSON对象中检索数据。

js文件:

var pieData = (function() {
        var json = null;
        $.ajax({
            'async': false,
            'global': false,
            'url': "http://127.0.0.1:8000/static/pwash/js/pie.json",
            'dataType': "json",
            'success': function (data) {
                json = data;
            },
            'error': function(data){
                console.log(data);
            }
        });
        return json;
    })();

    alert(pieData[0].value)

JSON:

[
                {
                    "value": 200,
                    "color":"#30a5ff",
                    "highlight": "#62b9fb",
                    "label": "Blue"
                },
                {
                    "value": 50,
                    "color": "#ffb53e",
                    "highlight": "#fac878",
                    "label": "Orange"
                },
                {
                    "value": 100,
                    "color": "#1ebfae",
                    "highlight": "#3cdfce",
                    "label": "Teal"
                },
                {
                    "value": 120,
                    "color": "#f9243f",
                    "highlight": "#f6495f",
                    "label": "Red"
                }
];

我无法理解我错在哪里。

3 个答案:

答案 0 :(得分:0)

使用路径访问本地json对象而不是http 最有可能的情况是:

"./static/pwash/js/pie.json"

答案 1 :(得分:0)

你的json文件有错误。你的json无效。它最后有分号。请删除它并尝试。

答案 2 :(得分:0)

请尝试这种和甜蜜的

$.getJSON('http://127.0.0.1:8000/static/pwash/js/pie.json', function (data) {
          console.log(data);
        });

json文件:

{
  "items": [

            {
                "value": 200,
                "color":"#30a5ff",
                "highlight": "#62b9fb",
                "label": "Blue"
            },
            {
                "value": 50,
                "color": "#ffb53e",
                "highlight": "#fac878",
                "label": "Orange"
            },
            {
                "value": 100,
                "color": "#1ebfae",
                "highlight": "#3cdfce",
                "label": "Teal"
            },
            {
                "value": 120,
                "color": "#f9243f",
                "highlight": "#f6495f",
                "label": "Red"
            }
       ]
}