我目前正在尝试向API发出跨域Ajax请求。我正在使用jQuery进行调用,并尝试从返回中解析出某些项目。
以下是请求:
$.ajax({
type: 'POST',
url: 'http://magicseaweed.com/api/APIKEY/forecast/?spot_id=665',
contentType: "text/plain",
dataType: "json",
xhrFields: {
withCredentials: false
},
success: function(data) {
timestamp = data[0].localTimestamp;
alert(timestamp);
},
error: function() {
alert("aw crap");
}
});
以下是回复:
[{
timestamp: 1366902000,
localTimestamp: 1366902000,
issueTimestamp: 1366848000,
fadedRating: 0,
solidRating: 0,
swell: {
minBreakingHeight: 1,
absMinBreakingHeight: 1.06,
maxBreakingHeight: 2,
absMaxBreakingHeight: 1.66,
unit: "ft",
components: {
combined: {
height: 1.1,
period: 14,
direction: 93.25,
compassDirection: "W"
},
primary: {
height: 1,
period: 7,
direction: 83.37,
compassDirection: "W"
},
secondary: {
height: 0.4,
period: 9,
direction: 92.32,
compassDirection: "W"
},
tertiary: {
height: 0.3,
period: 13,
direction: 94.47,
compassDirection: "W"
}
}
}]
目前,我只是想让时间戳字符串显示在警告框中。
这是我得到的错误:
Uncaught TypeError: Cannot read property 'localTimestamp' of undefined
at Object.success (app.js:11)
at i (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at A (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
我的错误在哪里?
答案 0 :(得分:1)
在您的ajax请求中,您已请求回复为contentType: "text/plain",
所以将其更改为application/json
或使用
data = JSON.parse(data);
答案 1 :(得分:0)
var parseData = JSON.parse(data); //turn json data to a javascript object
timestamp = parseData[0].localTimestamp; //then do something to the object