javascript - jQuery Ajax 请求 (CORS) 返回未定义

标签 javascript jquery ajax cors cross-domain

这是我第一次尝试向 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/

相关文章:

jquery - 一个div在另一个之上?

javascript - 仅当代码在 3 秒内未执行时才执行 block

javascript - 区分浏览器自动滚动和用户滚动

javascript - 使用 Ajax 运行 PHP 查询,以模式返回数据

javascript - 使用ajax发帖没有得到任何响应

javascript - 关闭模态后刷新父页面

javascript - 为什么io请求发送了那么多次?

javascript - 如何解析作为响应文本收到的 xml?

javascript - 只允许选择一些图像

jquery - ajax post后执行document.ready