我在文件中定义了一个 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;
}
* *已编辑 我也试过这个:
$.getJSON("myjson.json", function(data) {
alert("val");
var items = [];
$.each(data, function(key, val) {
alert(val);
});
});
但它不提醒任何东西意味着它没有获取 json 数据
它提醒未定义,请建议我一些获取值的方法,谢谢