【问题标题】:Error getting json data, ajax获取 json 数据时出错,ajax
【发布时间】:2015-08-17 16:32:21
【问题描述】:

我正在尝试从服务器获取数据而不使用 ajax 刷新页面,所以问题是数据像文本而不是 json 数据

我的代码:

$.ajax({
    type: "GET",
    url: "http://localhost:8080/search?key=" + QUERY + "",
    success: function (reslt) {
        console.log(reslt);
        console.log(reslt.length);
    }
});

以及服务器上的数据:

我使用nodejs和表达框架的代码:

router.get('/search', function (req, res) {
    tab = ['08:00', '09:00', '10:00', '11:00'];
    res.end(JSON.stringify(tab));
});

为什么当我做console.log(reslt[3]);时它给我8,应该给我10:00

【问题讨论】:

  • dataType: 'json' 添加到$.ajax() 调用中。
  • dataType:'json' 添加到您的ajax call
  • 在服务器端使用 JSON.stringify 并在成功处理程序中使用 JSON.parse 来访问数据的索引。

标签: javascript jquery ajax json node.js


【解决方案1】:

使用

dataType: 'json'

如果您的响应是 JSON,请始终将 datatype 设置为 json。这样做

$.ajax({
    type: "GET",
    dataType: 'json',
    url: "http://localhost:8080/search?key=" + QUERY + "",
    success: function (reslt) {
        console.log(reslt);
        console.log(reslt.length);
    }
});

【讨论】:

    【解决方案2】:

    您必须在 ajax 请求中使用 dataTypecontentType 属性

    $.ajax({
        type: "GET",
        dataType: 'json',
        contentType: "application/json",
        url: "http://localhost:8080/search?key=" + QUERY + "",
        success: function (reslt) {
            console.log(reslt);
            console.log(reslt.length);
        }
    });
    

    【讨论】:

    • contentType 可能不是必需的。 contentType 是您发送而不是接收的数据类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    • 2021-01-23
    相关资源
    最近更新 更多