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

使用Fetch API生成OrgChart时节点数据无法正常显示求助

问题诊断与解决方案

核心问题分析

你遇到的undefined节点及404问题,主要源于三个关键点:

  1. WebMethod请求格式错误:ASP.NET WebMethod要求POST请求必须携带JSON格式的请求体(即使是空对象),否则服务器无法识别WebMethod调用,返回404。
  2. 数据结构不匹配:
    • WebMethod返回的数据会被ASP.NET自动包装在d属性中,客户端需提取data.d获取实际数据。
    • 服务端返回的是数组类型的节点列表,但jquery.orgchart.js需要单个根节点对象作为数据源。
    • 插件默认使用小写children字段识别子节点,而服务端序列化后的字段是大写开头的Children,导致插件无法识别子节点及部分属性。
  3. 插件字段配置缺失:未明确指定插件对应服务端的子节点字段名,导致属性匹配失败。

分步解决方案

1. 修正客户端Fetch请求格式

在fetch调用中添加空JSON请求体,满足WebMethod的POST要求:

fetch("OrgCHart.aspx/GetOrgChartData", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({}) // 必须添加该参数,否则触发404
})

2. 调整数据提取与插件配置

修改数据处理逻辑,提取data.d中的第一个元素作为根节点,并配置插件识别服务端的大写字段:

.then(function (data) {
    $('#orgchart').orgchart({
        'data': data.d[0], // 取数组第一个元素作为根节点
        'nodeTitle': 'Name', // 匹配服务端的Name属性
        'nodeContent': 'Title', // 匹配服务端的Title属性
        'nodeChildren': 'Children' // 指定子节点字段为服务端的Children属性
    });
})

完整修正后的客户端代码

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>OrgChart</title>
    <script src="Scripts/jquery-3.4.1.js"></script>
    <script src="Scripts/jquery.orgchart.js"></script>
    <link rel="stylesheet" href="Content/jquery.orgchart.css" />
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            fetch("OrgCHart.aspx/GetOrgChartData", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify({})
            })
                .then(function (response) {
                    if (response.ok) {
                        return response.json();
                    } else {
                        throw new Error("Error: " + response.status);
                    }
                })
                .then(function (data) {
                    $('#orgchart').orgchart({
                        'data': data.d[0],
                        'nodeTitle': 'Name',
                        'nodeContent': 'Title',
                        'nodeChildren': 'Children'
                    });
                })
                .catch(function (error) {
                    console.log(error);
                });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div id="orgchart"></div>
    </form>
</body>
</html>

验证步骤

  1. 运行页面后,打开浏览器开发者工具(F12),查看Network标签下的请求是否返回200状态码,且JSON数据包含d属性。
  2. 确认返回的d数组第一个元素包含Name、Title、Children字段。
  3. 页面应正常显示CEO→VP→Manager的层级架构,无undefined节点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 01:27:10