2014-06-13 89 views
0

我正在嘗試從RESTful服務獲取JSON值。無法使用WCF REST服務獲取JSON值

我的服務:

namespace WcfService1 
{ 
    [ServiceContract] 
    public interface IService1 
    { 
     [OperationContract] 
     [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetUserDetails")] 
     string GetUserDetails(); 
    } 
} 

我從在瀏覽器中的服務獲取價值。

enter image description here

但是當我通過了jQuery在我的HTML頁面訪問它。它顯示錯誤。

<script type="text/javascript"> 
    $(document).ready(function() { 
     $('#BtnGetData').click(function() { 
      debugger; 
      $.ajax({ 
       type: "GET", 
       contentType: "application/json; charset=utf-8", 
       url: 'http://localhost:22727/Service1.svc/GetUserDetails', 
       data: "{}", 
       dataType: "json", 
       success: function (data) { 
        $($.parseJSON(data.d)).each(function (index, value) { 
         $("#tbDetails").append("<tr><td>" + value.Name + "</td><td>" + value.Email + "</td><td>" + value.Category + "</td><td>" + value.Mobile + "</td><td>" + value.Message + "</td></tr>"); 
        }); 
       }, 
       error: function (result) { 
        alert(result); 
       } 
      }); 
     }); 
    }); 
</script> 

我的服務方法:

public string GetUserDetails(string UserName, string Password) 
    { 
     if (UserName == "Admin" && Password == "123") 
     { 
      string file = AppDomain.CurrentDomain.BaseDirectory + "\\DataFile.xml"; 
      DataSet ds = new DataSet(); 
      JavaScriptSerializer serializer = new JavaScriptSerializer(); 
      List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>(); 
      Dictionary<string, object> row; 
      ds.ReadXml(file); 
      foreach (DataRow item in ds.Tables[0].Rows) 
      { 
       row = new Dictionary<string, object>(); 
       foreach (DataColumn col in ds.Tables[0].Columns) 
       { 
        row.Add(col.ColumnName, item[col]); 
       } 
       rows.Add(row); 
      } 
      return serializer.Serialize(rows); 
     } 
     else 
     { 
      return "null"; 
     } 
    } 

它顯示在控制檯中出現以下錯誤:

enter image description here

+0

當您是javascript ajax調用時始終運行服務 – KarthikManoharan

+0

它正在運行,但我無法獲取值。 @KarthikManoharan –

+0

查看此解決方案http://supportforums.blackberry.com/t5/Web-and-WebWorks-Development/WCF-webservice-calling-from-Jquery-ajax/mp/2716149#M42305 –

回答

0

我覺得JSON是格式不正確,應該想

"[{"Name" :"Nimit","Email:[email protected]"... 

這樣,我已經使用你的ajax調用我的服務它的工作fine.so錯誤在服務JSON格式不正確。

+0

因此,您能否建議正確的代碼? –

+0

[OperationContract] [WebGet(ResponseFormat = WebMessageFormat.Json)] List GetUserDetails(); – KarthikManoharan

+0

讓我發佈我的服務的GetUserDetails方法 –