简体   繁体   中英

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:

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

When I use a tool like firebug, I can see the JSON results:

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

However, when I call the "alert(result.d)" I get undefined. 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. I'd hesitate against using eval in your code because the security risks.

If you're using jQuery you can call jQuery.parseJSON(result) which will return the actual Javascript object you expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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