user1788736 user1788736 - 2 months ago 6
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 :

cordovaHTTP.post(url,data,
function(response) {
alert("Data: " + response.data + "\nStatus: " + response.status);

}


post request response received:

"[\r\n {\r\n \"itemID\": \"12345678\",\r\n \"itemTitle\": \"mango\",\r\n \"itemText\": \"\",\r\n \"ThumbUrl\": \"http://awebsite.com/pics/1.jpg\",\r\n \"Other\": null\r\n },\r\n {\r\n \"itemID\": \"12345679\",\r\n \"itemTitle\": \"orange\",\r\n \"itemText\": \"\",\r\n \"ThumbUrl\": \"http://awebsite.com/pics/2.jpg\",\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=http://somesite.com/12345678')">
<img src="http://awebsite.com/pics/1.jpg" alt=".." />
</a>
</div>

<div class ="image">
<a href="javascript:dofunction('./test.php?title=orange&TargetUrl=http://somesite.com/12345679')">
<img src="http://awebsite.com/pics/2.jpg" alt=".." />
</a>
</div>


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

You can write something like this:

cordovaHTTP.post(url, data, function(response) {
    // first, convert the string to JSON data array structure
    var json = $.parseJSON(response.data);
    // 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=http://somesite.com/" + json[i].itemID + "')\">" +
       "<img src=\""+ json[i].ThumbUrl +"\" alt=\"..\" />" +
       "</a>" +
       "</div>";
       // append it inside <body> tag.
       $("body").append(div);
    }
});
Comments