ail*_*mcm 12 c# asp.net jquery json httphandler
只是不明白我做错了..我一直在寻找几十个类似的问题,但仍然有误解......当我从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');
}
Run Code Online (Sandbox Code Playgroud)
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; }
}
Run Code Online (Sandbox Code Playgroud)
Adr*_*ode 24
尝试
data: JSON.stringify([{id: "10000", name: "bill"},{id: "10005", name: "paul"}])
Run Code Online (Sandbox Code Playgroud)
编辑我从属性名称中删除了引号
此外,需要以其他方式读取JSON字符串
string jsonString = String.Empty;
HttpContext.Current.Request.InputStream.Position = 0;
using (StreamReader inputStream = new StreamReader(HttpContext.Current.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)
工作解决方案
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;
}
}
Run Code Online (Sandbox Code Playgroud)