user1788736 user1788736 - 1 year ago 94
Javascript Question

How to loop over JSON post response and print its data into image divs?

I received JSON post response as shown below . I want to iterate over JSON post response data and print the data in image divs (as shown).

Could any show me how this can be done using JavaScript ? Thanks

Javascript code the receives JSON post response :,data,
function(response) {
alert("Data: " + + "\nStatus: " + response.status);


post request response received:

"[\r\n {\r\n \"itemID\": \"12345678\",\r\n \"itemTitle\": \"mango\",\r\n \"itemText\": \"\",\r\n \"ThumbUrl\": \"\",\r\n \"Other\": null\r\n },\r\n {\r\n \"itemID\": \"12345679\",\r\n \"itemTitle\": \"orange\",\r\n \"itemText\": \"\",\r\n \"ThumbUrl\": \"\",\r\n \"Other\": null\r\n }\r\n]"

Image divs that i want to print :

<div class ="image">
<a href="javascript:dofunction('./test.php?title=Mango&TargetUrl=')">
<img src="" alt=".." />

<div class ="image">
<a href="javascript:dofunction('./test.php?title=orange&TargetUrl=')">
<img src="" alt=".." />

Edit: I accept the answer below and i had to validate my actual api data using some replace functions by removing all \r\n and changing all itemText key values to "itemtext": "empty", using regular expression!

Answer Source

You can write something like this:, data, function(response) {
    // first, convert the string to JSON data array structure
    var json = $.parseJSON(;
    // then loop the single items
    for(i in json)
       // create HTML code
       var div = "<div class=\"image\">" + 
       "<a href=\"javascript:dofunction('./test.php?title=" + json[i].itemTitle + "&TargetUrl=" + json[i].itemID + "')\">" +
       "<img src=\""+ json[i].ThumbUrl +"\" alt=\"..\" />" +
       "</a>" +
       // append it inside <body> tag.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download