0

我从 jquery 对我的处理程序有一个非常简单的 ajax 调用,它无法检索数据,parsererror当我尝试在警报框中显示结果时它给了我。

ASP.NET 处理程序代码:

public void ProcessRequest (HttpContext context) {
          string json = new StreamReader(context.Request.InputStream).ReadToEnd();
        context.Response.ContentType = "application/json";
        context.Response.Write(json);
    }

jQuery

$('.submit').on("click",function(e) {
            e.preventDefault();
            var data1 = { "hi": "hello" };
            alert(data1.hi);
            $.ajax({
                  url: "/charity-challenge/CompetitionHelper.ashx",
                  data: data1,
                  dataType: 'json',
                  type: 'POST',
                  contentType: 'application/json; charset=utf-8',
                  success: function (data) {
                         alert("response = " + data);
                  },
                  error: function (data, status) {
                         alert("FAILED:" + status);
                  }
            });
      });

注意:我可以在调试时看到 chrome 中的响应很好。但不知何故,当我尝试在警报框中显示它时,它给了我解析器错误。

另外,我想在处理程序中分配 json 数据。我不知道该怎么做。

我在处理程序中有一个这样的示例。如何遍历 json 数据并将值分配给这些变量,以便我可以处理这些。

public class userData
      {
            public string EmailAddress { get; set; }
            public string EntryId { get; set; }
      }

找到了解决这个问题的方法。

我添加了一个完整的回调,现在它在警报框中显示结果。我不知道为什么没有它就无法工作,但如果有人知道,请发布答案。

这是完整的回调。

complete: function(xhr, status) {
            if (status === 'error' || !xhr.responseText) {
                alert("Error");
            }
            else {
                var data = xhr.responseText;
                alert(data);
                //...
            }
        }
4

1 回答 1

1

它与通过 ajax 调用作为 hi=hello 发送的请求有效负载有关

作为测试,试试这个(需要 Newtonsoft.Json nuget):

 public void ProcessRequest(HttpContext context)
 {
    //string json = new StreamReader(context.Request.InputStream).ReadToEnd();
    context.Response.ContentType = "application/json";
    context.Response.Write(JsonConvert.SerializeObject(new { hi = "hello" }));
 }

所以我想你必须解析你的输入流并正确生成 json。

您也可以在客户端解决此问题,方法是在 ajax 调用的数据参数中调用 JSON.stringify(data1)。

于 2013-06-12T03:50:20.417 回答