I have the following jQuery code. I am able to get the following data from server [{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]
. How do I iterate over this and fill a select box with id=combobox
$.ajax({ type: 'POST', url: "<s:url value="/ajaxMethod.action"/>", data:$("#locid").serialize(), success: function(data) { alert(data.msg); //NEED TO ITERATE data.msg AND FILL A DROP DOWN }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); }, dataType: "json" });
Also what is the difference between using .ajax
and $.getJSON
.
$. getJSON("http://www.example.com/path-to-get-data", function(data) { //iterate through each object and add it to the list. //ideally, the key and value (string to display to the end user) would be the same. });
append() method will add its argument to the dropdown as child element. The $('<option/>', { value: this, html: this }) will create a new <option> element that will get appended and safely set its inner HTML and value attribute to this . Now this inside the $. each refers to the current element that's being iterated.
This should do the trick:
$($.parseJSON(data.msg)).map(function () { return $('<option>').val(this.value).text(this.label); }).appendTo('#combobox');
Here's the distinction between ajax
and getJSON
(from the jQuery documentation):
[getJSON] is a shorthand Ajax function, which is equivalent to:
$.ajax({ url: url, dataType: 'json', data: data, success: callback });
EDIT: To be clear, part of the problem was that the server's response was returning a json object that looked like this:
{ "msg": '[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]' }
...So that msg
property needed to be parsed manually using $.parseJSON()
.
If your data is already in array form, it's really simple using jQuery:
$(data.msg).each(function() { alert(this.value); alert(this.label); //this refers to the current item being iterated over var option = $('<option />'); option.attr('value', this.value).text(this.label); $('#myDropDown').append(option); });
.ajax()
is more flexible than .getJSON()
- for one, getJson is targeted specifically as a GET request to retrieve json; ajax() can request on any verb to get back any content type (although sometimes that's not useful). getJSON internally calls .ajax().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With