JSON响应的问题,结果对象的属性被读取为未定义,但我可以看到它存在

Issue with JSON response, property of resultant object is being read as undefined but I can see it exists

本文关键字:我可以 未定义 存在 问题 响应 结果 对象 JSON 属性 读取      更新时间:2023-09-26

我有一个json响应,它是从一个表单的ajax请求中获得的。响应存储在一个名为response的变量中,如下所示:

{
    data: {
      attributes:{
            //list of key-values
        }
        id: null,
        type: "job"
    },
    links: {
      modal: "/client/render/modals/job/success"
    },
    message: "job successfully created",
    success: "ActionSuccess"
}

问题是当我尝试做:

response.links.modal

response['links']['modal']

我得到这个错误:

Uncaught TypeError: Cannot read property 'modal' of undefined

为什么它似乎认为链接不存在,当我可以看到它在JSON响应(我可以看到它存在于响应的预览(使用chrome))。

编辑:

发出ajax请求的代码:
function submit_form (request,method,data,type,target) {
    switch(type){
        case 'modal':
            $('#' + target).openModal();
        break;
        case 'target':
        break;
        case 'page':
        break
    }
    $.ajax({
        url: request,
        type: method,
        data: data,
        success: function(response){
            submit_callback(response,type,target)
        }
    })
}
回调:

function submit_callback(response,type,target) {
    switch(type){
        case 'modal':
            console.log(response) //shows that links exists
            console.log(response.links) //logs out as undefined
            post_page(response.links.modal,response.message,target) 
        break;
        case 'target':
            change_target(response,target);
            setUpPageElements();
        break
        case 'page':
            ('body').html(response)
        break;
    }
}
编辑:

使用JSON后的响应。对其进行字符串化:

"{'"message'":'"job successfully created'",'"success'":'"ActionSuccess'",'"data'":{'"attributes'":'"//list of key-values'"},'"type'":'"job'",'"id'":null},'"links'":{'"modal'":'"/client/render/modals/job/success'"}}"

仅供参考,属性确实存在,但不是解决这个问题所必需的,所以我已经删除了它们,它们实际上并没有说'"//list of key-values'"

好的,原来问题不在前端,而是在后端;由于某种原因,它没有返回json响应,而是作为文本,在摆弄代码后,我修复了这个问题,它现在返回json作为json而不是json字符串。

记住,孩子们,始终确保服务器返回正确的类型!