2014-03-19 56 views
2

我有以下的C#web服務(用於測試目的),我最終會變成一個WCFWebservice。Ajax調用C#webservice返回對象內的對象?

[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.ComponentModel.ToolboxItem(false)] 
[ScriptService] 
public class Albums : WebService { 

    [WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public Person GetPeople() { 
     return new Person("Mike", 12); 
    } 
} 

而且我把這個使用下面的JS:

$(document).ready(function() { 
     $.ajax({ 
      url: '/webservice/Albums.asmx/GetPeople', 
      contentType: "application/json; charset=utf-8;", 
      dataType: "json", 
      type: 'post', 
      success: function (data) { 
       console.log(data); 
      } 
     }); 
    }); 

但奇怪的事情(我)是,我不能在success()訪問data.Name。 不知何故,它增加了一個對象ddata。 因此,如果我想訪問名稱,我需要使用:data.d.Name

d從何而來?

+0

據我所知,這就是它的樣子。看看這個問題,如果你想改變行爲。 http://stackoverflow.com/questions/2811525/removing-the-d-object-from-asp-net-web-service-json-output – Steve

回答

2

這是沒有什麼可擔心的。它來自在服務器上使用OData協議:

這種模式確保了JSON有效載荷從OData的返回服務 有效的JSON語句,但不是有效的JavaScript語句。此 可防止由於跨站點腳本攻擊(XSS)攻擊導致執行OData JSON響應。

要了解細節,請參閱http://www.odata.org/documentation/odata-version-2-0/json-format

1

默認情況下,這既是OData格式化,也是一種安全措施。在ScriptMethod中添加以下內容即可輕鬆刪除該文件:

BodyStyle = WebMessageBodyStyle.Bare