Davor Zubak
Davor Zubak

Reputation: 4746

Generate multiple HTML elements from JSON using Jquery?

How to use Jquery and Javascript to extract JSON from $ajax and then do a foreach, and create a string that will append to html DOM?

Something like:

$(document).ready(function (e) {

$.ajax({
    type: "POST",
    url: "Companies/GetSearchRatios",
    context: this,
    success: function (data) {
       //return JSON
    }
});

Result JSON

[{"name":"MyNAme","value":350},{"name":"Hello","value":356}]

I can easily acces this values inside $ ajax method success, but how can I extract this value outside of method and use it to append to DOM?

This is what I need as a result of some for/foreach method:

  var $gElemRatios =
    '<option value=""></option>' +
    '<option value="350">MyNAme</option>' +
    '<option value="356">Hello</option>';

Then I use this var to combine with another:

 var $gElem =
    '<div class="cbox cboxQuarterWidth">' +
         '<select id="combobox_0">' +
               $gElemRatios + // here I add previous generated elem
         '</select>' +
    '</div>';

And finally:

$("#main").append($gElem);

Any ideas?

Upvotes: 0

Views: 1725

Answers (1)

m90
m90

Reputation: 11812

You can use $.each to loop through the data passed to the success handler:

$.ajax({
    type: "POST",
    url: "Companies/GetSearchRatios",
    context: this,
    success: function (data) {
       $.each(data,function(){
          console.log(this.name); //just an example how to access things
          $('#select').text(this.value); //maybe?
       });
    }
});

See this fiddle

Upvotes: 3

Related Questions