简体   繁体   English

尽管状态为200 OK,为什么AJAX JSON响应仍失败?

[英]Why is AJAX JSON response failing despite 200 OK status?

I am working on a basic ASP.NET & AJAX/JSON assignment and I am frustrated with making it work. 我正在进行基本的ASP.NET和AJAX / JSON分配,但对使其工作感到沮丧。 One of the requirements was to create an AJAX/JSON method to do some manipulations on SQL DB data. 要求之一是创建一个AJAX / JSON方法来对SQL DB数据进行一些操作。

In order to complete that, I used the following code: 为了完成此操作,我使用了以下代码:

In the aspx: 在aspx中:

    $.ajax({
              type: "GET",
              dataType: "json",
              url: "Retrieve",     
              success: function (data) {
                  alert(data);
                  var col;
                  for (col in data) {
                      alert(col);
                      addRow(data[col].id, data[col].Name, data[col].catagory, data[col].difficulty, data[col].company, data[col].price, '#products');
                  }
              },
              error: function () {
                  alert("1");

              }

In the "retrieve.aspx" page (the part of code that creates the data for JSON): 在“ retrieve.aspx”页面(为JSON创建数据的代码部分)中:

    Response.ContentType = "application/json; charset=utf-8";
            bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
            string category = Request.QueryString["category"];
            //string a = JsonConvert.SerializeObject(getProducts(category));
            var a = getProducts(category);
            // instantiate a serializer
            JavaScriptSerializer TheSerializer = new JavaScriptSerializer();

            var TheJson = TheSerializer.Serialize(a);
            Response.Write(TheJson);

And last but not least, if i try to change the dataType to text, it will show that the content is the JSON-structured text together with an HTML page code. 最后但并非最不重要的一点是,如果我尝试将dataType更改为text,它将显示内容是JSON结构的文本以及HTML页面代码。

What am I missing here? 我在这里想念什么?

You need to make sure ASP.NET does not render anything else outside of the json content you put into the response. 您需要确保ASP.NET不会在放入响应中的json内容之外呈现任何其他内容。 To do so, clear the response beforehand: 为此,请事先清除响应:

Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
...

and in the end complete the response right away: 最后立即完成响应:

Response.Write(TheJson);
HttpContext.Current.ApplicationInstance.CompleteRequest();

See this excellent answer as to why CompleteRequest should be used here instead of more widespread Request.End() . 关于为什么应在此处使用CompleteRequest而不是更广泛使用的Request.End() 最佳答案 ,请参见。

However using pages to output JSON seems like an overhead. 但是,使用页面输出JSON似乎很麻烦。 You may want to checkout simpler ways of doing the same, which is Http Handlers. 您可能想签出执行相同操作的更简单方法,即Http处理程序。 Plenty examples over the internet, here is one 互联网上有很多例子,这是一个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM