You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在jQuery ajax返回的Datatables结果中提取JSON指定字段值

实现方法

你只需要修改Datatables对应列的渲染逻辑,先把JSON字符串解析为对象,再按需读取指定字段即可,以下是具体代码示例:

1. 多个社交账号展示在同一列

columns: [
    {
        'data': null,
        'render': function(data) {
            // 兼容两种格式:如果返回的是JSON字符串先解析,是对象则直接使用
            const socialInfo = typeof data.social === 'string' ? JSON.parse(data.social) : data.social;
            // 自定义展示格式,没有对应账号时显示占位符-
            return `
                Twitter:${socialInfo.twitter || '-'}<br>
                Instagram:${socialInfo.instagram || '-'}<br>
                LinkedIn:${socialInfo.linkedin || '-'}
            `;
        },
        orderable: false
    }
]

2. 每个社交账号单独占一列

如果你要把不同平台的账号拆分到不同列,分别配置即可:

columns: [
    // 其他原有列配置保留
    {
        'data': null,
        'title': 'Twitter',
        'render': function(data) {
            const socialInfo = typeof data.social === 'string' ? JSON.parse(data.social) : data.social;
            return socialInfo.twitter || '-';
        }
    },
    {
        'data': null,
        'title': 'Instagram',
        'render': function(data) {
            const socialInfo = typeof data.social === 'string' ? JSON.parse(data.social) : data.social;
            return socialInfo.instagram || '-';
        }
    },
    {
        'data': null,
        'title': 'LinkedIn',
        'render': function(data) {
            const socialInfo = typeof data.social === 'string' ? JSON.parse(data.social) : data.social;
            return socialInfo.linkedin || '-';
        }
    }
]

优化建议

如果可以修改后端接口逻辑,建议直接在后端把social字段的JSON字符串解析为对象后再返回,前端就不需要重复执行JSON.parse,性能更好,代码也更简洁。

内容的提问来源于stack exchange,提问作者LarakBell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 04:24:02