Since whole afternoon I am trying to send some JSON response and capture them as select options.
I have tried formatting JSON string in various ways to get it retrieved via nested each() function of jQuery but could not get it right.
Right now my code looks like this:
Current JSON String Format:
{
"person1" : {"id":1, "name":"name1", "dob":"01-Jan-2016"},
"person2" : {"id":2, "name":"name2", "dob":"02-Jan-2016"},
"person3" : {"id":3, "name":"name3", "dob":"03-Jan-2016"},
"person4" : {"id":4, "name":"name4", "dob":"04-Jan-2016"}
}
I had also tried this format:
{
"persons" : [
{"id":1, "name":"name1", "dob":"01-Jan-2016"},
{"id":2, "name":"name2", "dob":"02-Jan-2016"},
{"id":3, "name":"name3", "dob":"03-Jan-2016"},
{"id":4, "name":"name4", "dob":"04-Jan-2016"}
]
}
JQuery
$.get().done()Handler:
var selectList = $("#personList");
var result = JSON.parse(data);
$.each(result, function(){
$.each(this, function(key, value){
alert(key + '=' + value);
selectList.append($("<options />").val(name).text(value));
});
});
Now in the alert boxes I can get all the key and value pair, but I want the <option>'s value to be filled up by person.id and text by person.name.
Which is not happening.
May be my JSON array string format is itself not correct.
Can anyone please help me out with these two piece of codes?