这是我第一次尝试向 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);
返回为未定义。我的错误在哪里?
最佳答案
timestamp = data[0].localTimestamp;
不是
timestamp = data.localTimestamp;
因为响应是一个包含一项的数组[{...}]
关于javascript - jQuery Ajax 请求 (CORS) 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42120241/