我有一个按钮,在按钮单击中我想使用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!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
}
答案 0 :(得分:1)
您正在尝试执行跨域Ajax请求,但由于它违反了same-origin policy,因此无效。
然而,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!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
请注意,不需要使用$.parseJSON(data)
,因为jQuery会自动为您解析响应,data
已经是对象。
答案 1 :(得分:0)
尝试这样的事情
更改此
dataType: 'json',
到
dataType: 'jsonp',