简体   繁体   中英

apply for loop on json response (multidimensional) to get value

{
  "Search": [{
    "Title": "Batman Begins",
    "Year": "2005",
    "imdbID": "tt0372784",
    "Type": "movie",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg"
  }, {
    "Title": "Batman",
    "Year": "1989",
    "imdbID": "tt0096895",
    "Type": "movie",
    "Poster": "http://ia.media-imdb.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg"
  }],
  "totalResults": "291",
  "Response": "True"
}

Above is my json response. I want to get title values by using jQuery.

I tried below code... I'm sending request each time when user insert character in text box (on keyup ):

url = "https://www.omdbapi.com/?s=" + value;
$.getJSON(url, {
  get_param: 'value'
}, function(data) {
  $.each(data, function(index, element) {
    //console.log(data);   
  });
  for (var prop in data) {
    var item = data[prop];
    for (var d in item) {
      var title = item[d];
      console.log(title);
    }

  }
});

You can use Jquery.each() function to iterate over both arrays and object. It takes to arguments either array or object as the first argument and a callback function. since the response is in form of an object you need to run another Jquery.each() on the array holding the objects if you want to implement some logic before that, or just run Jquery.each() on the array it's self:

Here is a sample code that prints the titles on the console:

$.getJSON(url, { get_param: 'value' }, function(data) {
            $.each(data.Search, function(index, value) {
              console.log(value.Title);
            });

        });

And here is a JSFiddle

$.each(data.Search, function(obj){          
   alert(obj.Title);
});

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