从我的客户端,我将json数据发送到data.ashx文件,但是我无法从ashx文件的ProcessRequest方法读取数据。只是不明白为什么我越来越空
这样我将数据从客户端发送到ashx文件
var FeedCrd = {};
FeedCrd["Name"] = $("input[id*='txtName']").val();
FeedCrd["Subject"] = $("input[id*='txtSubject']").val();
FeedCrd["Email"] = $("input[id*='txtFEmail']").val();
FeedCrd["Details"] = $("textarea[id*='txtDetails']").val();
$.ajax({
type: "POST",
url: urlToHandler + "?ac=send",
data: JSON.stringify(FeedCrd),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data == "SUCCESS");
{
//
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
这是我的ProcessRequest的ashx文件代码
public void ProcessRequest(HttpContext context)
{
string outputToReturn = "";
context.Response.ContentType = "text/html";
if (context.Request.QueryString["ac"] == "send")
{
string sName = context.Request["Name"];
string sSubject = context.Request["Subject"];
outputToReturn = "SUCCESS";
}
context.Response.Write(outputToReturn);
}
我还看到了如何使用firebig将数据发送到服务器端。这是数据
{“名称”:“ cvv”,“主题”:“ fdsfd”,“电子邮件”:“ [email protected]”,“详细信息”:“哇”}
所以请帮我从客户端发送json时如何从ashx文件读取数据。请告诉我我在哪里弄错了。请指导我。谢谢
最佳答案
要注意的第一点是确保始终在上下文中检查null或Empty字符串。
接下来,您的响应应该是JSON对象,但是您只是返回一个String。
从.ashx处理程序发送之前,构造为JSON
public void ProcessRequest(HttpContext context)
{
string outputToReturn = String.Empty; // Set it to Empty Instead of ""
context.Response.ContentType = "text/json";
var ac = string.Empty ;
var sName = String.Empty ;
var sSubject = String.Empty ;
// Make sure if the Particular Object is Empty or not
// This will avoid errors
if (!string.IsNullOrEmpty(context.Request["ac"]))
{
ac = context.Request["ac"];
}
if (ac.Equals("send")) // Use Equals instead of just = as it also compares objects
{
if (!string.IsNullOrEmpty(context.Request["Name"]))
{
sName = context.Request["Name"];
}
if (!string.IsNullOrEmpty(context.Request["Subject"]))
{
sSubject = context.Request["Subject"];
}
// You need to Send your object as a JSON Object
// You are just sending a sting
outputToReturn = String.Format("{ \"msg\" : \"{0}\" }", "SUCCESS" ) ;
}
context.Response.Write(outputToReturn);
}
//在这种情况下,您的ajax应该看起来像这样
$.ajax({
type: "POST",
url: urlToHandler + "?ac=send",
data: JSON.stringify(FeedCrd),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
if( data != null){
if (data.msg == "SUCCESS"); {
alert( data.msg)
}
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
关于jquery - 如何从ashx文件读取JSON数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12584785/