简体   繁体   English

将json数据传递给javascript变量

[英]Pass json data to javascript variable

Probably a simple one for an expert: 对于专家来说可能是一个简单的方法:

I have a json file called newport.json located in the www folder. 我在www文件夹中有一个名为newport.json的json文件。 The json is as follows: json如下:

{"nmech":"3.00","nelect":"3.00","nplant":"0.00","ncivil":"55.00"}

I have my JS to load in via ajax: 我有我的JS通过ajax加载:

$.ajax({
    url:'newport.json',
    datatype:'json',
    type:'get',
    cache:false,
    success:function(data){
        $(data).each(function(index,value){
                console.log(value);

        });
    }
}); 

My issue is the console log produces the following from the above js: 我的问题是控制台日志从上述js生成以下内容:

Object {nmech: "3.00", nelect: "3.00", nplant: "0.00", ncivil: "55.00"}

but I seem to be struggling to then get a value say nmech passed into a javascript variable. 但是我似乎很努力地要获得一个值,例如nmech传递给javascript变量。

Thanks in advance for any help. 在此先感谢您的帮助。

Your json is an object , not array . 您的json是一个对象 ,而不是数组 As soon as you don't have anything to enumerate, $.each doen's make much sense here. 一旦您没有要枚举的内容,$。each确实在这里很有意义。

To to access you properties you need: 要访问您的属性,您需要:

var nmech = data.nmech;
var nelect = data.nelect;

etc 等等

As there is a single object that is returned, the loop only runs once. 由于返回了单个对象,因此循环仅运行一次。 I believe what you are trying to do is to enumerate the properties of that single object. 我相信您想要做的是枚举该单个对象的属性。 So this: 所以这:

for (var propertyName in data) { console.log(data[propertyName]; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM