Reputation:
I Have a JSON file named destinations.json and i would like to get the data from this file to display in a dropdown box on HTML. The JSON file is as shown below
{
"Destinations": [
{
"destinationName": "London",
"destinationID": "lon"
},
{
"destinationName": "New York",
"destinationID": "nyc"
},
{
"destinationName": "Paris",
"destinationID": "par"
},
{
"destinationName": "Rome",
"destinationID": "rom"
}
]
}
So far, i have made sure the jquery library is available and then created a function which will fetch data from the JSON file when clicked, shown below.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#fetch').click(function() {
$.post('http://jonathangatenby.co.uk/Candidate/json/destinations.json', {}, function(data) {
$.each(data.Destinations, function(i, v) {
$('#destinations').append('<option value="' + v.destinationID + '">' + v.destinationName + '</option>');
});
});
});
</script>
from here, i have simple HTML which will give me a drop down box.
<select id="destinations">
<option value="">Select</option>
</select>
<a href="#" id="fetch">Fetch JSON</a>
This doesn't seem to work, and all the files are on the same server.
Upvotes: 3
Views: 554
Reputation: 7063
Try this jquery code :
$(function() {
$('#fetch').click(function(){
$.getJSON('yourjsonfile.json', function(data) {
destinations = data['Destinations']
$.each(destinations, function(id, destination) {
$('select').append('<option value="">'+destination["destinationName"]+'</option>')
})
});
})
})
Upvotes: 1