我有一个按钮,在按钮点击中,我想使用AJAX调用获取JSON数据,这是我在按钮点击时尝试的代码。但不起作用
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!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
}
您正在尝试执行一个跨域Ajax请求,但由于它违反了同源策略,因此该请求不起作用。
然而,api.flightstats.com网站似乎确实支持jsonp——至少,当我将您的URL修改为:时
https://api.flightstats.com/flex/airports/rest/v1/jsonp/iata/SAN?appId=952b68c2&appKey=9d5a372da9f88679ac97a60c1e0c58f9
// Note the "p" that I've added here -----------------^
它返回了一个jsonp格式的响应。所以试试这个代码:
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!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
演示:http://jsfiddle.net/Lc8H8/
请注意,不需要使用$.parseJSON(data)
,因为jQuery会自动为您解析响应,并且data
将已经是一个对象。
尝试类似的东西
更改此
dataType: 'json',
至
dataType: 'jsonp',