2013-05-28 38 views
0

我试图从jQuery传递JSON到.ASHX文件。 我想通过HttpContext和猫到NameValueCollection检索.ASHX文件中的JSON数据。 这是怎么回事?将jsondata转换为NameValueCollection

$.ajax({ 
    url: "GetLetterInformationHandler.ashx", 
    data: "{'Name':'david', 'Family':'logan'}", 
    contentType: "application/json; charset=utf-8", 
    type: "Get", 
    datatype: "json", 
    onSuccess: function (data) { 

    } 
}); 

现在我可以使用查询字符串,并与投如下:

public void ProcessRequest(HttpContext context) 
    { 
     HttpResponse response = context.Response; 
     string cururl = context.Request.Url.ToString(); 
     int iqs = context.Request.Url.ToString().IndexOf('?'); 
     string querystring = (iqs < cururl.Length - 1) ? cururl.Substring(iqs + 1) : String.Empty; 
     NameValueCollection parameters = HttpUtility.ParseQueryString(querystring); 
     context.Response.ContentType = "text/plain"; 
    } 

我想用JSON insted的查询字符串

回答

0

的试试这个:

$.map(data.d, function (item) { 
    return { 
     name: item.Name, 
     family: item.Family 
    }; 
}) 

或者,如果你想要每个功能:

var resultData = data.d; 
$.each(resultData, function() { 
    alert(this) 
}) 
+0

我使用动态parameters.Also其他地区的应用程序发送参数到ashx – ZSH

0

我已经做了一些改动希望这将帮助你:)

的Ajax功能

$.ajax({ 
    type: "POST", 
    url: "GetLetterInformationHandler.ashx", 
    data: "{'Name':'david', 'Family':'logan'}", 
    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); 
     } 
    }); 

.ashx的文件

public void ProcessRequest(HttpContext context) 
{  
    string outputToReturn = String.Empty; // Set it to Empty Instead of ""   
    context.Response.ContentType = "text/json";  

    var getName = String.Empty ;  
    var getFamily = String.Empty ;  // Make sure if the Particular Object is Empty or not 
    if (!string.IsNullOrEmpty(context.Request["Name"]))   
    {   
     getName = context.Request["Name"];   
    } 

    if (!string.IsNullOrEmpty(context.Request["Subject"]))   
    {    
     getFamily = context.Request["Subject"];   
    } 

    NameValueCollection nvc = new NameValueCollection(); 
    nvc.Add(getName, getFamily); 
    var dict = new Dictionary<string, string>(); 
    foreach (string key in nvc.Keys) 
    { 
     dict.Add(key, nvc[key]); 
    } 
    string json = new JavaScriptSerializer().Serialize(dict); 
    Console.WriteLine(json); 
} 
+0

我编辑我的问题以澄清问题。您的示例是静态参数 – ZSH

+0

@ZSH我做了一些改变!我希望它能帮助你 – webGautam

相关问题