0

ファイルにjson配列を次のように定義しました

{
    mainServiceBar= [
        { "mainServiceName":"ECONOMIC SERVICES" , "mainServiceValue":"23.2" },
        { "mainServiceName":"SOCIAL SERVICES" , "mainServiceValue":"34.5" },
        { "mainServiceName":"DEFENSE" , "mainServiceValue":"4.5" },
        { "mainServiceName":"GENERAL PUBLIC SERVICES" , "mainServiceValue":"19" },
        { "mainServiceName":"DEBT BURDEN" , "mainServiceValue":"18.8" },
    ];


    subServiceBar1: [
        { "subServiceName":"agriculture" , "subServiceValue":"12.5" },
        { "subServiceName":"trade" , "subServiceValue":"12.5" },
        { "subServiceName":"tourism" , "subServiceValue":"12.5" },
        { "subServiceName":"power and energy" , "subServiceValue":"12.5" },
        { "subServiceName":"water resource" , "subServiceValue":"12.5" }
        { "subServiceName":"communication roads" , "subServiceValue":"12.5" }
        { "subServiceName":"other economic services" , "subServiceValue":"12.5" },
        { "subServiceName":"subsidy" , "subServiceValue":"12.5" },
    ];
}

今、私はJavaScript関数でこれらのjson配列の値が必要です。いくつかのことをしましたが、値を取得できませんでした。私のコードは次のとおりです。

function getJsonArray() {
    return $.getJSON("myjson.js"); 
}

function socialservice(thisv) {
    json = getJsonArray();

    for (var key in json) {
        if (json.hasOwnProperty(key)) {
            var item = json[key];

            alert(item.mainServiceName);
        }
    }

    return false;
}

* *EDITED 私もこれを試しました:

$.getJSON("myjson.json", function(data) {
    alert("val");

    var items = [];

    $.each(data, function(key, val) {
        alert(val);
    });
});

しかし、何も警告しません。jsonデータを取得しないことを意味します

undefined と警告します , 値を取得する方法を教えてください , ありがとう

4

3 に答える 3

1

getJson docに従って、データを操作するためにコールバックを記述する必要があります。

$.getJSON( "myjson.js", function( json ) {
    for (var key in json) {
          // code
    }
});

注意: 投稿された JSON コードは無効です。エラーがたくさんあります。これに置き換えてみてください:

{
    "mainServiceBar": [
        { "mainServiceName":"ECONOMIC SERVICES" , "mainServiceValue":"23.2" },
        { "mainServiceName":"SOCIAL SERVICES" , "mainServiceValue":"34.5" },
        { "mainServiceName":"DEFENSE" , "mainServiceValue":"4.5" },
        { "mainServiceName":"GENERAL PUBLIC SERVICES" , "mainServiceValue":"19" },
        { "mainServiceName":"DEBT BURDEN" , "mainServiceValue":"18.8" }
    ],
    "subServiceBar1": [
        { "subServiceName":"agriculture" , "subServiceValue":"12.5" },
        { "subServiceName":"trade" , "subServiceValue":"12.5" },
        { "subServiceName":"tourism" , "subServiceValue":"12.5" },
        { "subServiceName":"power and energy" , "subServiceValue":"12.5" },
        { "subServiceName":"water resource" , "subServiceValue":"12.5" },
        { "subServiceName":"communication roads" , "subServiceValue":"12.5" },
        { "subServiceName":"other economic services" , "subServiceValue":"12.5" },
        { "subServiceName":"subsidy" , "subServiceValue":"12.5" }
    ]
}
于 2013-09-20T07:21:43.257 に答える