jQuery to display/load images received from JSON file
Related Post:
- How to Read and Parse JSON using jQuery
- jQuery- Parse JSON, XML and HTML
- Read and Process XML using jQuery Ajax
Consider, below is the JSON file content. It has products list with name and its image path.
{ "products": [ { "name": "Levis Blue Denim", "imgPath": "images/prods/levisbluedemin01.jpg" }, { "name": "Pepe Black Jeans", "imgPath": "images/prods/pepeblackjeans01.jpg" }, { "name": "Pepe Blue Jeans", "imgPath": "images/prods/pepebluejeans01.jpg" } ] }
First, read the JSON file using $.getJSON function and then iterate through the received json result. Within the loop, fetch the imgPath property value, set it as image source to <img> tag and append it to a variable.
And once all the products are processed then add the variable value to DOM element in which images needs to be displayed.
$(document).ready(function () { var jsonURL = "productList.json"; $.getJSON(jsonURL, function (json) { var imgList= ""; $.each(json.products, function () { imgList += '<li><img src= "' + this.imgPath + '"></li>'; }); $('#dvProdList').append(imgList); }); });
Feel free to contact me for any help related to jQuery, I will gladly help you.