I have to display images to the browser and I want to get the image from a JSON response and display it to the browser using Javascript. This is what the JSON response looks like:
var champion = [
{
"name":"Aatrox",
"img" : "Aatrox.png"
},
{ "name":"Ahri",
"img" : "Ahri"
},
{
"name":"Akali",
"img" : "Akali.png"
},
{ "name":"Alistar",
"img" : "Alistar.png"
},
{ "name":"Amumu",
"img" : "Amumu.png"
}
]
The JSON is an external file, called data.json. I am a beginner. I wrote this code:
var champ = JSON.stringify(champion);
//var mydata = JSON.parse(champion);
var images = 'mylink/';
var counter;
var name;
for(counter=0; counter<5 ; counter++ ){
var liTag = document.createElement("li"); //create li tag
liTag.setAttribute("class","champ-list");
document.getElementById("myul").appendChild(liTag); //attach the new tag li on ul tag
var divChamp = document.createElement("div"); //create "champ" div
divChamp.setAttribute("class" , "champ-div");
document.getElementsByClassName("champ-list")[0].appendChild(divChamp); //attack the new tag div on li tag
var spanBox = document.createElement("span"); //new span tag
spanBox.setAttribute("class","champ-box");
document.getElementsByClassName("champ-div")[0].appendChild(spanBox); //attack the new tag span on div tag
var imgTag = document.createElement("img"); //new img tag
images +=champ[counter].img;
imgTag.setAttribute("class", "champ-icon");
imgTag.setAttribute("alt", "champ");
imgTag.setAttribute("src", images );
document.getElementsByClassName("champ-box")[0].appendChild(imgTag); //attach the new tag img on span tag
name = champ[counter].name;
var divName = document.createElement("div"); //new div tag
divName.setAttribute("class","champ-name");
divName.innertHTML=name;
document.getElementsByClassName("champ-icon")[0].appendChild(divName); //attack the new tag div on img tag
}
It does not display the name and image, but returns a value of undefined.
Another problem is that the first li tag is inserted 5 div, then in the first div there are 5 span, the first span there are 5 img tag and the first img tag there are 5 div. How do I solve all these problems?
var champion =at the start. But then you should load it via an Ajax request, so you can get it assigned to the variable of your choice.jsonyou tagged your question with.