JSON调用返回'未定义'

JSON call returning 'undefined'

本文关键字:未定义 调用 返回 JSON      更新时间:2023-11-21

我对使用JSON还比较陌生,遇到了一个似乎无法解决的问题。我已经设置了一个通用处理程序(下面详细介绍),还有一个带有JSON调用的页面,用于从处理程序中获取响应并进行呈现

带有JSON调用的页面是:

<script type="text/javascript">
    $(document).ready(function () {
        triggerCall();
        function triggerCall() {
            $.ajaxSetup({
                type: 'POST',
                headers: { "cache-control": "no-cache" }
            });
            $.ajax
              (
                {
                    type: "POST",
                    url: "Services/DepartmentListHandler.ashx",
                    contentType: "application/json;charset=utf-8",
                    dataType: "json",
                    async: false,
                    cache: false,
                    success: function (data) {
                        alert(data.msg);
                        displayDirectory(data.msg);
                    },
                    error: function (x, e) {
                        alert("The call to the server side failed. " + x.responseText);
                    }
                }
              );
        }
        function displayDirectory(dirlist) {
            var tablestring = '<table class="centered-table"><tr><td colspan="2">';
            tablestring = tablestring + "<tr><td><u>DeptCode</u></td><td><u>HeaderText</u></td></tr>";
            for (var i = 0, len = dirlist.length; i < len; ++i) {
                tablestring = tablestring + "<tr>";
                tablestring = tablestring + "   <td>" + dirlist[i].DeptCode + "</td>";
                tablestring = tablestring + "   <td>" + dirlist[i].HeaderText + "</td>";
                tablestring = tablestring + "</tr>";
            }
            tablestring = tablestring + "</table>";
            $('#divDirectoryList').html(tablestring);
        }
    });
    </script>

<div id="divDirectoryList"></div>

处理方法是:

Public Class DepartmentListHandler
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    Dim json = New JavaScriptSerializer()
    Dim lst As New List(Of DepartmentList)
    Dim cls1 As New DepartmentList(1, 0, "DEP1", "Header", 1, True, False)
    lst.Add(cls1)
    Dim serialisedList As String = json.Serialize(lst)
    context.Response.ContentType = "application/json"
    context.Response.Write(serialisedList)
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
    Get
        Return False
    End Get
End Property
End Class

所有可能发生的情况是,"success"分支中的警报每次都返回"undefined",并且表根本没有呈现。

有人看到我哪里错了吗?

非常感谢!

我认为您在代码中序列化的json数据格式不正确。显示为"data.msg"的json数据必须作为接收

{
    msg: 'some message',
    data:'some data'
};

实际上,在客户端,您将获得对象的[object object]集合,该对象包含您的对象列表。

打印console.log("数据",data);看看火狐。

您可以简单地获得

data[0].msg;
data[0].id;

或者你可以用jquery迭代java脚本对象,然后得到下面的

data.msg;
data.id