2013-03-19 59 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