ASP.NET JQuery AJAX POST返回数据但在401响应中
我的应用程序中有一个Web页面,需要调用我已设置的Web服务来返回对象列表。 此调用设置如此
$(document).ready(function() { var response = $.ajax({ type: 'POST', contentType: 'application/json; charset=utf-8', url: '/Ajax/service.asmx/GetObjects' }); response.success(function(data) { $('#bodyText').html(data); }); response.complete(function() { alert('ajax complete'); }); });
我的服务看起来像这样
namespace AjaxTest.Ajax { #region using System.ComponentModel; using System.Web.Script.Serialization; using System.Web.Script.Services; using System.Web.Services; #endregion /// /// Summary for boat /// [WebService(Namespace = "http://quality/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.Web.Script.Services.ScriptService] public class Boat : WebService { #region Public Methods and Operators /// /// The Get Models method. /// [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public void GetModels() { var models = Com.somedll.GetModels(); var serializer = new JavaScriptSerializer(); var response = models.Count != 0 ? serializer.Serialize(models) : serializer.Serialize(new Error { Code = "500", Message = "Model Retrieval Failed" }); this.Context.Response.Clear(); this.Context.Response.ContentType = "application/json"; this.Context.Response.Flush(); this.Context.Response.Write(response); } #endregion } }
我收到以下错误服务器无法在HTTP标头发送后附加标头。 并且看着Firebug,请求似乎被发送多次,每次请求至少4次,任何人都可以帮忙。 如果您需要更多信息,请与我们联系
在调用Flush
之前移动Response.Write
调用。
this.Context.Response.Write(response); this.Context.Response.Flush();
更新 :您还可以尝试删除ContentType
设置器,因为您已经声明您的响应类型是JSON。
你可以尝试剥离它:
this.Context.Response.Clear(); this.Context.Response.ContentType = "application/json"; this.Context.Response.Flush(); this.Context.Response.Write(response);
只是:
this.Context.Response.Write(response);
甚至
this.Context.Response.BufferOutput = true; this.Context.Response.Write(response); this.Context.Response.End();
编辑
听起来你可能会遇到这种行为:
- 你写一些东西来回复
- 你冲洗了
- 您的代码触发错误,asp.net尝试重写标头,这是不允许的,因为对Flush()的调用已经写入标头
坚持尝试捕捉那里,看看是否有任何东西抛出。