JavaScript Array of objects to a dropdown
I have an array of objects which was fetched from a JSON (JSONP)
file using jQuery.
I'm required to display this data using an HTML dropdown.
Current code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type='text/ja开发者_如何学Pythonvascript'>
$.getJSON('remote-json-proxy.php?lang=en&callback=?', function(data){
console.log(data);
})
</script>
How do I put this data
variable which is array of objects to be displayed using HTML drop-down?
object array looks like this
Object
lines: Array[10]
0: Object
line: "COLOMBO - BADULLA"
1: Object
2: Object
3: Object
4: Object
5: Object
6: Object
7: Object
JSON File
( {"lines":[{"line":"COLOMBO - BADULLA"},{"line":"COLOMBO - MATALE"},{"line":"COLOMBO - PUTTLAM"},{"line":"COLOMBO - THANDIKULAM"},{"line":"COLOMBO - TALAIMANNAR"},{"line":"COLOMBO - BATTICALOA"},{"line":"COLOMBO - TRINCOMALEE"},{"line":"COLOMBO - MATARA"},{"line":"COLOMBO - AVISSAWELLA"},{"line":"COLOMBO - MIHINTALE"}]} );
This should work:
$(document).ready(function() {
var oDDL = $("<select>");
$.getJSON('remote-json-proxy.php?lang=en&callback=?', function(data) {
$.each(data.lines, function(i, item) {
oDDL.append('<option>' + item.line + '</option>');
});
});
$("body").append(oDDL);
});
As you can see, it's building drop down list object and appending options
to it for every item in the JSON array.
Note: Each JSON response is different, the data.lines
and item.line
match the JSON format of this specific case only.
You'd first have to create a element in your html if you don't have one:
<select id='myselect'></select>
Then, in your js, assuming you have properties .value
y .caption
per item you would do:
$.getJSON('remote-json-proxy.php?lang=en&callback=?', function(data){
for(var i=0; i<data.length; i++){ //Traverse the data array
var value = data[i].value;
var text = data[i].caption;
$('<option/>').val(value).text(text).appendTo('#myselect');
};
});
Just that. Hope this helps. Cheers
精彩评论