Pass json data to javascript variable

时间:2016-02-12 20:53:59

标签: javascript jquery json ajax

Probably a simple one for an expert:

I have a json file called newport.json located in the www folder. The json is as follows:

 <input type="number" name="font_size_number" id="txtNumber">
 <text id="txtOutput">This is the output area.</text>

 <script>
    window.addEventListener("load", function(){
         var txtNumber = document.getElementById('txtNumber');
         var txtOutput = document.getElementById('txtOutput');
         txtNumber.addEventListener("change", function(){
              txtOutput.style.fontSize = txtNumber.value + "px";
         });
    );
 </script>

I have my JS to load in via ajax:

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

My issue is the console log produces the following from the above js:

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

        });
    }
}); 

but I seem to be struggling to then get a value say nmech passed into a javascript variable.

Thanks in advance for any help.

2 个答案:

答案 0 :(得分:1)

Your json is an object, not array. As soon as you don't have anything to enumerate, $.each doen's make much sense here.

To to access you properties you need:

<c:forEach />

etc

答案 1 :(得分:0)

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:

import