【问题标题】:Unable to access nested value in JSON string from ajax response无法从 ajax 响应访问 JSON 字符串中的嵌套值
【发布时间】:2018-03-30 01:23:24
【问题描述】:

我知道对此有多个问题,但没有一个答案对我有用

我通过 .ajax 响应从 PHP 返回编码后的 JSON 字符串

$.ajax({
    url : ajax_object.ajax_url,
    type : 'post',
    data : {
        action: 'rt_check_for_new_messages',
        uid : $uid,
        pid : $pid,
        sessionStart : $sessionStart,
        room_array :$roomArray,
        messages_array : $messagesArray,   
    },
    dataType : "json",
    success: function(data) {
        console.log(data);

在控制台中我得到

{html: "[]", messageData: "[{"roomName":"master","msgID":1638}, {"roomName":"beta","msgID":1640}]"}

所以现在我需要访问“roomName”以便过滤掉匹配项

var matches = $(data).filter(function(i,n) {
    return n.messageData[].roomName === 'master';
});
console.log(matches);

我尝试了所有我能找到的组合

【问题讨论】:

    标签: json ajax filter nested


    【解决方案1】:

    n.messageData[].roomName === 'master'; 不是有效的 JavaScript 语法。

    我相信这是你需要做的:

    var matches = $(JSON.parse(data.messageData)).filter(function(i,n) {
        return n.roomName === 'master';
    });
    

    请注意,我在这里解析 data.messageData - 根据您向我们展示的控制台输出,看起来 messageData 是一个包含 JSON 的字符串,而不是一个数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 2018-12-06
      相关资源
      最近更新 更多