这是我第一次尝试向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.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"
}
}
}]
目前,我只想让时间戳字符串显示在警告框中。
alert(timestamp);
以未定义的形式返回。我的错误在哪里?
答案 0 :(得分:3)
timestamp = data[0].localTimestamp;
不是
timestamp = data.localTimestamp;
因为响应是包含一个项目[{...}]