我有一个支持WCF Ajax的Web服务,我通过jquery调用它。当我通过返回一个字符串来测试它时返回正常。一旦我添加了更多功能,javascript错误回调就会运行而没有有用的数据。只是说'错误',readystate = 0,status = 0。
我可以单步执行服务代码,并成功返回一个对象数组。然而,客户不会。
这是代码。
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class WebAPI
{
[OperationContract]
[WebGet(ResponseFormat=WebMessageFormat.Json)]
public Person[] GetPeople(Guid groupId)
{
using (SchedulerContext context = new SchedulerContext())
{
return context.People.Where(p=>p.Group_ID==groupId).ToArray();
}
}
}
在客户端:
<script type="text/javascript">
$(document).ready(function () {
$.ajax(
{
type: "GET",
dataType: "json",
contentType: "json",
data: { groupId: 'ae09a080-5d7c-4e92-9a87-591574b7c4b8' },
url: "WebAPI.svc/GetPeople",
error: function (error) {
alert("error");
},
success: function (msg) {
alert(msg.d);
}
}
);
});
</script>
更新 使用fiddler检查它,http结果为504,并且在'raw'响应选项卡中有以下内容:
HTTP/1.1 504 Fiddler - Receive Failure
Content-Type: text/html; charset=UTF-8
Connection: close
Timestamp: 13:52:46.107
[Fiddler] ReadResponse() failed: The server did not return a response for this request.
更新 - 2012/05/04: (顺便说一下,大家都欢乐星球大战!) 我发现问题出在JSON序列化中。它在我的实体模型上给出了循环引用异常。仍在研究解决方案。
答案 0 :(得分:0)
您可以采取一些措施来调试此问题:
$.ajax
来电中使用错误功能中的额外参数。 error callback takes 3 parameters(jqXHR,textStatus,errorThrown),您可以在jqXHR中查询其status
或responseText
属性,这些属性可以为您提供有关错误的更多信息。答案 1 :(得分:0)
您可以将服务方法定义修改为以下内容:
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class WebAPI
{
[OperationContract]
[WebGet(UriTemplate="GetPeople/{groupId}",ResponseFormat=WebMessageFormat.Json)]
public Person[] GetPeople(Guid groupId)
{
using (SchedulerContext context = new SchedulerContext())
{
return context.People.Where(p=>p.Group_ID==groupId).ToArray();
}
}
}
现在执行来自Fiddler的GET请求,请求如下:
GET http://localhost:15006/WebAPI.svc/GetPeople/739526F1-7C58-4E3B-97D8-4870948BFE32 HTTP/1.1
Content-Type: application/json
User-Agent: localhost
现在尝试从jquery调用中执行相同操作,并查看请求的外观。