获取json数据错误,ajax

Error getting json data, ajax

本文关键字:ajax 错误 数据 json 获取      更新时间:2023-09-26

我试图从服务器获得数据而不使用ajax刷新页面,因此问题数据像文本而不是像json数据

my code:

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

和服务器上的数据:

我使用nodejs和express框架的代码:

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'

如果您的响应是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);
    }
});

您必须在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);
    }
});