只是不明白我做错了什么..
我一直在寻找数十个类似的问题,但仍然存在误解......
当我从 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; }
}
Try
data: JSON.stringify([{id: "10000", name: "bill"},{id: "10005", name: "paul"}])
edit我删除了属性名称中的引号
另外,还需要读取JSON字符串以其他方式 https://stackoverflow.com/questions/3466163/help-reading-json-from-httpcontext-inputstream
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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)