[英]Getting data In AJAX call
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 我有一个按钮,然后单击按钮,我想使用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!!!!!!!!!!!!!!!!!!!!!!!!');
}
});
}
You are trying to do a cross-domain Ajax request, which doesn't work because it violates the same-origin policy . 您正在尝试执行跨域Ajax请求,因为它违反了同源策略 ,所以该请求不起作用。
However, the api.flightstats.com site does appear to support jsonp - at least, when I modified your URL to this: 但是,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 -----------------^
...it returned a response in jsonp format. ...它以jsonp格式返回响应。 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/ 演示: 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. 注意,不需要使用$.parseJSON(data)
因为jQuery会自动为您解析响应,并且data
已经是一个对象。
try something like this 尝试这样的事情
change this 改变这个
dataType: 'json',
to 至
dataType: 'jsonp',
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.