简体   繁体   English

ASP.NET WebMethod返回对象为json但不在响应方法中

[英]ASP.NET WebMethod returning object as json but not in response method

I have a simple webmethod: 我有一个简单的网络方法:

<WebMethod(Description:="Does something.")> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Shared Function ReturnJSONData() As Person
    Dim guy As New Person
    guy.Name = "Joe"
    guy.Age = 8
    Return guy
End Function

and here is where I am calling the ajax method: 这是我调用ajax方法的地方:

 function GetPerson() {
     PageMethods.ReturnJSONData(OnWSRequestComplete1);
 }
 function OnWSRequestComplete1(result) {
     alert(result.d);
 }

When I use a tool like firebug, I can see the JSON results: 当我使用Firebug之类的工具时,可以看到JSON结果:

{"d":{"__type":"Person","Name":"Joe","Age":8}}

However, when I call the "alert(result.d)" I get undefined. 但是,当我调用“ alert(result.d)”时,我的状态不确定。 Am I missing something? 我想念什么吗?

When you get a response from a WebMethod, you need to eval the response because it is returned as a string. 从WebMethod获得响应时,您需要评估响应,因为它以字符串形式返回。 I'd hesitate against using eval in your code because the security risks. 我会犹豫不要在您的代码中使用eval ,因为存在安全风险。

If you're using jQuery you can call jQuery.parseJSON(result) which will return the actual Javascript object you expect. 如果您使用的是jQuery,则可以调用jQuery.parseJSON(result) ,它将返回您期望的实际Javascript对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM