Reputation: 4746
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
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