简体   繁体   中英

Issue calling JSON object property value with Jquery and Javascript

I am trying to call an object property value and append it to the div "file-path-info". The function that appends JSON data to "file-size-info" works. What am I doing wrong with my second statement?

My JSON data:

{"maxFileSize" : "10 MB", "fileList" :  [{"fileName" : "1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat", "href" : "../Images/1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat.jpg"}]}

HTML and JavaScript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="file-size-info"></div>
<div id="file-path-info"></div>

<script>

    $.getJSON('http://localhost/MISREST/helpdocs', function (data) {
  $.each( JSON.parse(data), function ( key, val ) {
    if (key == "maxFileSize") {$("#file-size-info").append(val);};

      if (key == "fileList") {$("#file-path-info").append(["fileList"]["href"]);};

  });
    });

</script>

It should be

if (key == "fileList") {
   $("#file-path-info").append(val[0]["href"]);
};

assuming you only have one value in fileList , if not then you need to loop over the values.

as for the fileList key , val gives you

[
  {
    "fileName": "1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat",
    "href": "../Images/1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat.jpg"
  }
]

and then you need to extract href from the first object.

if (key == "maxFileSize") {$("#file-size-info").append(val);};

In that block of code maxFileSize is the key and val is the value of that property (the string 10 MB ).

Following that pattern, when fileList is the key, val would be the value of that property: [{"fileName" : "1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat", "href" : "../Images/1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat.jpg"}] (an array containing a single item that is an object).

You'll need to index the array to get the item at index 0 (the only item) and grab the value of that object's href property in order to use it:

if (key == "fileList") {$("#file-path-info").append(val[0].href);};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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