一尘不染

将jquery json传递到asp.net httphandler

json

只是不明白我在做错什么。.我一直在寻找许多类似的问题,但仍然存在误解…当我从JS调用CallHandler函数时,我总是收到“请求失败”警报。请帮我。

JS / jQuery:

function CallHandler() {
    $.ajax({
        url: "DemoHandler.ashx",
        contentType: "application/json; charset=utf-8",
        type: 'POST',
        dataType: "json",
        data: [{"id": "10000", "name": "bill"},{"id": "10005", "name": "paul"}],
        success: OnComplete,
        error: OnFail
    });
    return false;
}

function OnComplete(result) {
    alert(result);
}
function OnFail(result) {
    alert('Request Failed');
}

asp.net C#代码背后:

public void ProcessRequest(HttpContext context)
{
  JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
  string jsonString = HttpContext.Current.Request.Form["json"];

  List<Employee> emplList = new List<Employee>();
  emplList = jsonSerializer.Deserialize<List<Employee>>(jsonString);

  string resp = "";
  foreach (Employee emp in emplList){
  resp += emp.name + " \\ ";
  }
  context.Response.Write(resp);
}

public class Employee
{
  public string id { get; set; }
  public string name { get; set; }
}

阅读 243

收藏
2020-07-27

共1个答案

一尘不染

尝试

data: JSON.stringify([{id: "10000", name: "bill"},{id: "10005", name: "paul"}])

编辑 我从属性名称中删除了引号

另外,JSON字符串需要以其他方式读取

string jsonString = String.Empty;

HttpContext.Current.Request.InputStream.Position = 0;
using (StreamReader inputStream = new StreamReader(HttpContext.Current.Request.InputStream))
{
     jsonString = inputStream.ReadToEnd();
}

一个可行的解决方案

public void ProcessRequest(HttpContext context)
{
    var jsonSerializer = new JavaScriptSerializer();
    var jsonString = String.Empty;

    context.Request.InputStream.Position = 0;
    using (var inputStream = new StreamReader(context.Request.InputStream))
    {
        jsonString = inputStream.ReadToEnd();
    }

    var emplList = jsonSerializer.Deserialize<List<Employee>>(jsonString);
    var resp = String.Empty;

    foreach (var emp in emplList)
    {
        resp += emp.name + " \\ ";
    }

    context.Response.ContentType = "application/json";
    context.Response.ContentEncoding = Encoding.UTF8;
    context.Response.Write(jsonSerializer.Serialize(resp));
}

public class Employee
{
    public string id { get; set; }
    public string name { get; set; }
}

public bool IsReusable
{
    get
    {
        return false;
    }
}
2020-07-27