Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery fill dropdown with json data

Tags:

json

jquery

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.

like image 818
user373201 Avatar asked May 10 '11 15:05

user373201


People also ask

How to append JSON data to dropdownlist in jquery?

$. 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. });

How to bind JSON value to dropdownlist in jquery?

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.


2 Answers

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().

like image 135
namuol Avatar answered Oct 22 '22 03:10

namuol


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().

like image 25
Tejs Avatar answered Oct 22 '22 04:10

Tejs