I'm a J Query beginner. Need some help with the $.getJSON function. I am trying to retrieve data from an outside server using this function but when I run it, I get nothing. I've been through countless tutorials. Heres my code sample...
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var url='https://api.flightstats.com/flex/airports/samples/v1/lts/Airport_response.json';
$('#button').click(function(){
$.getJSON(url,function(json){
$("#results").append(json.airport.name);
});
});
});
</script>
</head>
<body>
<input type="button" id="button" value="Go">
<div id="results"></div>
</body>
and heres the JSON file content..
{
"airport":
{
"fs":"PDX",
"iata":"PDX",
"icao":"KPDX",
"faa":"PDX",
"name":"Portland International Airport",
"street1":"7000 NE Airport Way",
"city":"Portland",
"cityCode":"PDX",
"stateCode":"OR",
"postalCode":"97218",
"countryCode":"US",
"countryName":"United States"
}
}
Im just trying to grab the 'name' content. Is $.getJSON the correct function or should I use $.ajax or $.get? Thanks
The issue here is that .getJSON is not able to return data for that url.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.flightstats.com/flex/airports/samples/v1/lts/Airport_response.json. This can be fixed by moving the resource to the same domain or enabling CORS.
If you control the website flightstats.com you can add the necessary headers for that. If you don't you probably want to create a lightweight server side fetch to display the necessary json using proper CORS responses.
For more information than I can easily place in a stackoverflow page about CORS, please see https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS