我目前正在尝试向 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)
我的错误在哪里?
最佳答案
在您的ajax请求中,您请求的响应为contentType: "text/plain",
因此将其更改为 application/json
或使用
data = JSON.parse(data);
关于javascript - jQuery 跨源 Ajax 请求上未捕获的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42123336/