【发布时间】:2014-04-30 16:04:27
【问题描述】:
我在 WCF (demo) 中做了一项 Rest 服务,输出为:{"GetEmployeeJSONResult":{"Id":101,"Name":"Sumanth","Salary":5000}}
现在我在 asp.net 中创建了一个网站,我在其中通过 AJAX JSON 调用这个休息服务...
我的代码如下:
<script type="text/javascript">
$(document).ready(function () {
// $.getJSON("http://localhost/SampleService/Service1.svc/getJson?callback=?", null, function (data) {
// alert(data.Name);
// });
var endpointAddress = "http://localhost/SampleService/Service1.svc";
var url = endpointAddress + "/GetJson";
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
contentType: 'application/json',
data: "{}",
success: function (result) {
//alert(JSON.stringify(result));
alert(result.length);
},
error:function(jqXHR)
{
alert(jqXHR.status);
}
});
});
</script>
你可以看到我已经通过 AJAX 和 getJSON 方法访问了服务..
现在当我发出数据警报时,它显示我的输出为未定义..
我努力了 :
alert(result.d.length) , alert(result.d.GetEmployeeJSONResult) 但在这两种方法中总是显示为未定义..
我的 WCF 服务代码如下:
namespace WcfServiceXmlAndJsonDemo
{
[ServiceContract]
public interface IService1
{
#region OperationContracts
[OperationContract]
[WebInvoke(Method="GET",UriTemplate="GetXml",ResponseFormat=WebMessageFormat.Xml,RequestFormat=WebMessageFormat.Xml,BodyStyle=WebMessageBodyStyle.Bare)]
EmployeeXML GetEmployeeXML();
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "GetJson", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
List<EmployeeJSON> GetEmployeeJSON();
#endregion
}
}
DataContract EmployeeJSON:
namespace WcfServiceXmlAndJsonDemo
{
[DataContract]
public class EmployeeJSON
{
#region Properties
[DataMember]
public string Name { get; set; }
[DataMember]
public int Id { get; set; }
[DataMember]
public double Salary { get; set; }
#endregion
}
}
Service1.svc.cs:
namespace WcfServiceXmlAndJsonDemo
{
public class Service1 : IService1
{
public List<EmployeeJSON> GetEmployeeJSON()
{
EmployeeJSON json = new EmployeeJSON()
{Name="Sumanth",Id=101,Salary=5000.00 };
return json;
}
}
}
请帮我解决这个问题..
提前谢谢你。
克鲁纳尔
【问题讨论】:
-
您应该尝试从 fiddler 或任何请求跟踪工具获取请求,以确保服务正常工作,然后继续使用 Ajax。如果您在 fiddler 中遇到任何类型的错误,请在此处提及。
标签: c# javascript ajax json wcf