2013-03-19 52 views
-1

讀返回對象在JQuery中 4分鐘前| LINK讀返回對象在JQuery中

我創建了一個WCF服務,返回GenericList對象。我需要閱讀使用jQuery在客戶端該對象,但可以得到它的工作:

下面

是我的代碼:

SVC方法:

[OperationContract] 
    [WebGet(ResponseFormat = WebMessageFormat.Json)] 
    public CommentList GetComments() 
    { 
     Comments oComment1 = new Comments(); 
     oComment1.Title = "AMaking hay when the sun shines"; 
     oComment1.Author = "Plan_A"; 
     oComment1.CommentText = "AI like hay almost as much as I like sun. Just joking"; 

     Comments oComment2 = new Comments(); 
     oComment2.Title = "Making hay when the sun shines"; 
     oComment2.Author = "Plan_B"; 
     oComment2.CommentText = "I like hay almost as much as I like sun. Just joking"; 

     CommentList oCommentList = new CommentList(); 
     oCommentList.Comment.Add(oComment1); 
     oCommentList.Comment.Add(oComment2); 

     return oCommentList; 
    } 
在客戶端

jQuery腳本:

$('#CommentsButton').click(function() { 
     $.getJSON('http://localhost:55679/RESTService.svc/GetComments?callback=?', function (data) { 
       alert(data); 

     }); 

響應我越來越(通過Inspect元素 - 鉻工具)

jsonp1363710839478({"Comment":[{"Author":"Plan_A","CommentText":"AI like hay almost as much as I like sun. Just joking","Title":"AMaking hay when the sun shines"},{"Author":"Plan_B","CommentText":"I like hay almost as much as I like sun. Just joking","Title":"Making hay when the sun shines"}]}); 
+0

問題是什麼? – Matus 2013-03-19 16:57:07

+0

'alert(GetComments);'中定義的'GetComments'在哪裏? – 2013-03-19 16:59:58

+0

@Matus我需要讀取從 – Khan 2013-03-19 17:07:04

回答

1

試試這個:

$.getJSON('http://localhost:55679/RESTService.svc/GetComments?callback=?', function (data) { 
    alert(data.Comments[0].Author); 
}); 
+0

後面的代碼中定義的Getcomments函數得到的值不確定'&'是否有效,但我不確定'callback =?'無論是。 :) – 2013-03-19 16:58:24

+0

@DavinTryon回調是針對jsonp的,而對於「&」不確定他的網址是如何構建的,只是認爲他試圖通過參數。 :S – 2013-03-19 16:59:35

+0

看起來你已經改變了'?'到'&'的網址。那是故意的嗎?因爲通常你會看到'http:// host/action?var = value' – 2013-03-19 17:01:06

1

這工作。

$.ajax({ 
     type : "GET", 
     dataType : "jsonp", 
     url : 'http://localhost:55679/RESTService.svc/GetComments', 
     success: function(data){ 
      console.log(data.Comment.length); 
      for(var i=0; i<data.Comment.length; i++){ 
       console.log(data.Comment[i].Title); 
      } 
     } 
    }); 
+0

它不工作,它不顯示任何東西。 – Khan 2013-03-19 17:35:42

+0

@Khan,我創建了一個示例WCF服務器並在發佈之前對其進行了測試。當然,它的工作原理....(你是否在瀏覽器中打開了控制檯窗口(參見代碼中的'console.log'),或者用'alert'替換它) – I4V 2013-03-19 17:40:18