ashx文件获取$.ajax()方法发送的数据

2020-05-29 07:17:50易采站长站整理

//contentType: 'application/json; charset=utf',
cache: false,
dataType: 'json',
success: function (data) {
alert(data.key + "|" + data.key);
},
error: function (xhr) {
alert("出现错误,请稍后再试:" + xhr.responseText);
}
});

可是结果还是一样的,使用context.Request[“key3”]还是获取不到参数,没办法,既然常规的方式获取不到,那就另寻他法吧,百度了一下,找到了解决办法,在ashx中使用如下的方式就可以获取到了,首先写一个通用的获取参数的方法,代码如下:


/// <summary>
/// 获取参数
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private Dictionary<String, Object> GetParameter(HttpContext context)
{
StreamReader reader = new StreamReader(context.Request.InputStream);
//得到json字符串:strJson={"key":"xdp-gacl","key":"白虎神皇"}
String strJson = HttpUtility.UrlDecode(reader.ReadToEnd());
JavaScriptSerializer jss = new JavaScriptSerializer();
//将json字符串反序列化成一个Dictionary对象
Dictionary<String, Object> dicParameter = jss.Deserialize<Dictionary<String, Object>>(strJson);
return dicParameter;
}

GetParameter方法返回一个dicParameter对象,dicParameter就存放了从$.ajax方法中提交到ashx中的参数,如下图所示:

这样就可以从dicParameter中取出传递过来的参数作处理了,完整代码如下:


public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string operFlag = context.Request["operFlag"];
if (operFlag == "test")
{
string key = context.Request["key"];
string key = context.Request["key"];
string resStr = key + "|" + key;
context.Response.Write(resStr);
}
else if (operFlag == "test")
{
Dictionary<String, Object> dicParameter = GetParameter(context);
string key = dicParameter["key"].ToString();
string key = dicParameter["key"].ToString();
string resStr = "{"key":"" + key + "", "key":"" + key + ""}";
context.Response.Write(resStr);
}
}

以上所述是小编给大家介绍的ashx文件获取$.ajax()方法发送的数据,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对软件开发网网站的支持!