我使用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',并且表格根本不会呈现。
谁能看到我出错的地方?
非常感谢!
答案 0 :(得分:0)
我认为您在我们的代码中序列化的json数据格式不正确。显示为“data.msg”的json数据必须作为
接收{
msg: 'some message',
data:'some data'
};
答案 1 :(得分:0)
实际上在客户端,您将获得对象的[object Object]集合,该对象包含您的对象列表。
打印 的console.log( '数据',数据);并在火狐中看到。
您可以简单地
data[0].msg;
data[0].id;
或者你可以用jquery迭代java脚本对象然后得到如下
data.msg;
data.id