简体   繁体   中英

How to load data from external json file using jquery?

This is my app.js file

$(document).ready(function () {
        $.getJSON("http://localhost:3000/db.json", function (data) {

        $(data.as).each(function (index, value) {

            console.log(value);
        });
    });
});

and this is db.json file

{
  "as": [
    {
      "imageID": "1",
      "imageSource": "Popular Science 1",
      "alt": "Science 1"
    },
    {
      "imageID": "2",
      "imageSource": "Popular Science 2",
      "alt": "Science 2"
    }
  ]
}

How to get only, for example, Popular Science 2 ? if I write console.log(value[1]); , an error is displayed. How to index an array?

You can simply use:

value.imageSource

as value is the object here.

 const data = {as:[{imageID:"1",imageSource:"Popular Science 1",alt:"Science 1"},{imageID:"2",imageSource:"Popular Science 2",alt:"Science 2"}]}; $(data.as).each(function(index, value) { console.log(value.imageSource); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


If you only want Popular Science 2 , then there is no need to loop. You can simply do:

 const data = {as:[{imageID:"1",imageSource:"Popular Science 1",alt:"Science 1"},{imageID:"2",imageSource:"Popular Science 2",alt:"Science 2"}]}; console.log( data.as[1].imageSource );

Or, with some validation like:

 const data = {as:[{imageID:"1",imageSource:"Popular Science 1",alt:"Science 1"},{imageID:"2",imageSource:"Popular Science 2",alt:"Science 2"}]}; // Vlidating that we actually have an array and data as index 1 if( data && data.as && data.as.length > 1){ console.log( data.as[1].imageSource ); }

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