javascript - jQuery 跨源 Ajax 请求上未捕获的类型错误

标签 javascript jquery json ajax

我目前正在尝试向 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 或使用

将字符串解析为 Json
data = JSON.parse(data);

关于javascript - jQuery 跨源 Ajax 请求上未捕获的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42123336/

相关文章:

json - postman jetpacks - 测试嵌套数据

javascript - jquery中json循环后的命令

javascript - 防止空白输入不起作用

javascript - Angular 1.5 在 ng-repeat 上隐藏重复值

javascript - 在 javascript/knockout.js 中创建 2dim 数组表

jquery - 使用 Watir 测试拖放

背景图像的 jquery 选择器

ajax - Grails 通过向对象的键添加方括号 [] 来错误地解释发布的 JSON 数据

javascript - jquery 高度返回 0

json - 如何将 $ref 与 json-schema 和顶级属性一起使用