使用WEB API的Ajax Jquery请求

我正在尝试从WEB API调用中检索JSON结果。

我的WEP API方法:

[AcceptVerbs("GET", "POST")] public object GetTest() { rep = new ChatRepository(); chatBoxCLS box = rep.Chatrequest(chatRequestLevel.Parent, null); System.Web.Mvc.JsonResult jsonResult = new System.Web.Mvc.JsonResult { Data = box, JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet }; return jsonResult.Data; } 

我已经修改了WebapiConfig.cs,如下所示,它将始终返回JSON

  config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { action = "get", id = RouteParameter.Optional } ); var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"); config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); 

下面是我的Jquery ajax调用:

  $(document).ready(function () { $.ajax({ type: 'GET', url: 'http://localhost:6606/api/values/GetTest', dataType: 'json', crossDomain: true, success: function (msg) { alert('success'); }, error: function (request, status, error) { alert('error'); } }); });  

它始终以错误警报结束。 没有从WEB API收到任何数据。 我尝试调试,发现我的请求成功点击WEB API方法并返回JSON。 下面是它返回的JSON数据。

{“listOfItems”:[{“id”:14,“description”:“New test”,“display_number”:1},{“id”:4,“description”:“operational”,“display_number”:2} ,{ “ID”:3 “描述”: “销售”, “display_number随后”:3},{ “ID”:5 “描述”: “技术”, “display_number随后”:4}], “回复”:空, “历史”:空, “Initialhistory”:空, “问题”: “”, “chatids”:空, “displayNum”:空}

为什么我在客户端没有得到任何结果?

我通过将Access-Control-Allow-Origin添加到响应头来解决了这个问题

 public class CrossDomainActionFilter : ActionFilterAttribute { public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { bool needCrossDomain = true; if (needCrossDomain) { actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*"); } base.OnActionExecuted(actionExecutedContext); } } [AcceptVerbs("GET", "POST")] [CrossDomainActionFilter] public object GetTest() { rep = new ChatRepository(); chatBoxCLS box = rep.Chatrequest(chatRequestLevel.Parent, null); System.Web.Mvc.JsonResult jsonResult = new System.Web.Mvc.JsonResult { Data = box, JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet }; return jsonResult.Data; }