i have a button and in the button click i wanted to get a JSON data using AJAX call,here is the code which i tried in button click.But its not working
function loadXMLDoc() {
var request = $.ajax({
url: 'https://api.flightstats.com/flex/airports/rest/v1/json/iata/SAN?appId=952b68c2&appKey=9d5a372da9f88679ac97a60c1e0c58f9',
type: 'POST',
//data: $("#ganttForm").serialize(),
dataType: 'json',
accepts: {
json: "application/json"
},
headers: {
Accept: "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
success: function (data) {
alert('success')
var data1 = $.parseJSON(data);
alert(data1);
//console.log(window.JSON.parse(data));
//alert(obj.ganttdata)
//console.log($.parseJSON(data.d));
//console.log(JSON.stringify(data1));
createEmptyGanttChart1(data1);
},
complete: function () {
alert('complete')
// console.log('complete 1!!!!!!!!!!!!!!!!!!!!!!!!');
},
failure: function () {
alert('failure')
// console.log('complete 1!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
}
You are trying to do a cross-domain Ajax request, which doesn't work because it violates the same-origin policy .
However, the api.flightstats.com site does appear to support jsonp - at least, when I modified your URL to this:
https://api.flightstats.com/flex/airports/rest/v1/jsonp/iata/SAN?appId=952b68c2&appKey=9d5a372da9f88679ac97a60c1e0c58f9
// Note the "p" that I've added here -----------------^
...it returned a response in jsonp format. So try this code instead:
var request = $.ajax({
url: 'https://api.flightstats.com/flex/airports/rest/v1/jsonp/iata/SAN?appId=952b68c2&appKey=9d5a372da9f88679ac97a60c1e0c58f9',
type: 'POST',
//data: $("#ganttForm").serialize(),
dataType: 'jsonp', // NOTE the type is 'jsonp' not 'json'
success: function (data) {
alert('success')
alert(data);
createEmptyGanttChart1(data); // NOTE no need to parse data
},
complete: function () {
alert('complete')
// console.log('complete 1!!!!!!!!!!!!!!!!!!!!!!!!');
},
failure: function () {
alert('failure')
// console.log('complete 1!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
Demo: http://jsfiddle.net/Lc8H8/
Note that there is no need to use $.parseJSON(data)
because jQuery automatically parses the response for you and data
will already be an object.
try something like this
change this
dataType: 'json',
to
dataType: 'jsonp',
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.