用ajax提交数据到ashx用JSON.stringify格式化参数后在服务器端取不到值?[转载至:http://q.cnblogs.com/q/34266/]
前台代码:
$(function () {
var model = function (key) {
this.key = key;
}
var m = new model("abc");
$.ajax({
url: '/Demo.ashx',
type: 'POST',
data: JSON.stringify(m),
contentType: 'application/json; charset=utf8',
cache: false,
dataType: 'text',
success: function (data) {
alert(data);
},
error: function (xhr) {
alert("出现错误,请稍后再试:" + xhr.responseText);
}
});
});
Demo.ashx:
public class Demo : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World" + context.Request.Form["key"]);
}
public bool IsReusable
{
get
{
return false;
}
}
}
运行后弹出 "Hello World":
改为下面这样就可以了:
$.ajax({
url: '/Demo.ashx',
type: 'POST',
//data: JSON.stringify(m),
//contentType: 'application/json; charset=utf8',
data:{key:"abc"},
cache: false,
dataType: 'text',
success: function (data) {
alert(data);
},
error: function (xhr) {
alert("出现错误,请稍后再试:" + xhr.responseText);
}
});
如图:
有人知道为什么吗?
我主要是想弄明白为什么用 JSON.stringify格式化参数 取不到值