2010-06-01 92 views
40

我试图从jQuery传递JSON到.ASHX文件。下面的jQuery示例:ASP.NET - 从JQuery传递JSON到ASHX

$.ajax({ 
     type: "POST", 
     url: "/test.ashx", 
     data: "{'file':'dave', 'type':'ward'}", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json",  
    }); 

如何检索我的.ASHX文件中的JSON数据?我有方法:

public void ProcessRequest(HttpContext context) 

,但我无法找到在请求中的JSON值。

+0

样本将帮助您的回复 http://stackoverflow.com/a/19824240/1153856 – OsmZnn 2013-12-10 13:54:09

回答

-3

尝试System.Web.Script.Serialization.JavaScriptSerializer

随着铸造字典

+2

感谢。你能否详细说明一下?我应该序列化什么对象? – 2010-06-01 10:04:38

+0

@colin,我喜欢字典,但你可以坚持任何对象,例如在你的示例中:class MyObj {public String file,type; } – Dewfy 2010-06-01 12:03:17

4

如果你将数据发送到服务器相对于$.ajax数据不会被自动转换成JSON数据(见How do I build a JSON object to send to an AJAX WebService?)的。因此,您可以使用contentType: "application/json; charset=utf-8"dataType: "json"并保持不要将数据与JSON.stringify$.toJSON转换。取而代之的

data: "{'file':'dave', 'type':'ward'}" 

(手动数据转换成JSON),你可以尝试使用

data: {file:'dave', type:'ward'} 

context.Request.QueryString["file"]context.Request.QueryString["type"]结构获得服务器端的数据。如果您收到了一些问题,这样,那么你可以尝试用

data: {file:JSON.stringify(fileValue), type:JSON.stringify(typeValue)} 
在服务器端

和使用DataContractJsonSerializer。如果使用$阿贾克斯和使用.ashx的获取查询字符串

+0

感谢您的回复。我遇到的问题是,当我使用ASHX页面时,无法将JSON数据放入请求对象中。 context.Request.QueryString [“file”]的值始终为空。你会知道如何获取JSON数据到请求中吗? – 2010-06-01 11:13:59

+0

为了能够使用'context.Request.QueryString [“file”]查看'file'参数''你应该使用'data'如'data:{file:'dave',type:'ward'}'(参见我的回答)。然后,将定义名称为'file'和'type'的查询参数,并将发布到服务器的数据编码为'file = dave?type = ward'。 – Oleg 2010-06-01 11:27:39

+2

如果您的AJAX是POSTing,那么数据将位于Request.Form属性中,而不是QueryString。 – 2010-09-21 17:01:00

-1

,不设置数据类型

$.ajax({ 
    type: "POST", 
    url: "/test.ashx", 
    data: {'file':'dave', 'type':'ward'}, 
    **//contentType: "application/json; charset=utf-8", 
    //dataType: "json"**  
}); 

我得到它的工作!

1

这适用于调用Web服务。不确定.ASHX

$.ajax({ 
    type: "POST", 
    url: "/test.asmx/SomeWebMethodName", 
    data: {'file':'dave', 'type':'ward'}, 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function(msg) { 
     $('#Status').html(msg.d); 
    }, 
    error: function(xhr, status, error) { 
     var err = eval("(" + xhr.responseText + ")"); 
     alert('Error: ' + err.Message); 
    } 
}); 



[WebMethod] 
public string SomeWebMethodName(string file, string type) 
{ 
    // do something 
    return "some status message"; 
} 
0

您必须在web配置文件中定义处理程序属性来处理用户定义的扩展请求格式。这里的用户定义的扩展名是 “.API”

添加动词= “*” 路径= “test.api” 类型= “测试” 更换URL: “/test.ashx”url:“/test.api”

23

以下解决方案为我工作:

客户端:

 $.ajax({ 
      type: "POST", 
      url: "handler.ashx", 
      data: { firstName: 'stack', lastName: 'overflow' }, 
      // DO NOT SET CONTENT TYPE to json 
      // contentType: "application/json; charset=utf-8", 
      // DataType needs to stay, otherwise the response object 
      // will be treated as a single string 
      dataType: "json", 
      success: function (response) { 
       alert(response.d); 
      } 
     }); 

服务器端。ASHX

using System; 
    using System.Web; 
    using Newtonsoft.Json; 

    public class Handler : IHttpHandler 
    { 
     public void ProcessRequest(HttpContext context) 
     { 
      context.Response.ContentType = "text/plain"; 

      string myName = context.Request.Form["firstName"]; 

      // simulate Microsoft XSS protection 
      var wrapper = new { d = myName }; 
      context.Response.Write(JsonConvert.SerializeObject(wrapper)); 
     } 

     public bool IsReusable 
     { 
      get 
      { 
       return false; 
      } 
     } 
    } 
+0

它不适合我这样,但是:'string myName = context.Request [“firstName”]'; – Jaanus 2013-08-01 14:33:12

+0

@Jaanus你使用POST吗? – Andre 2013-09-12 11:59:34

+0

@Andre能否获得{firstName:'stack',lastName:'overflow'}完整的字符串。我不需要分裂。请给出解决方案http://stackoverflow.com/questions/24732952/receive-the-jsonquery-string-in-webmethod?noredirect=1#comment38367134_24732952 – Sagotharan 2014-07-14 09:51:40

49

我知道这是太旧了,但仅仅是为了记录我想加我5分钱

你可以用这个

string json = new StreamReader(context.Request.InputStream).ReadToEnd(); 
+0

这是让它正常工作的正确方法。完善。 – 2012-03-25 00:28:24

+0

这是最重要的5美分。我想补充一点,如果你不介意。 – naveen 2012-09-18 06:35:17

+0

@Claudio Redi请帮我解决这个问题... http://stackoverflow.com/questions/24732952/receive-the-jsonquery-string-in-webmethod?noredirect=1#comment38367134_24732952 – Sagotharan 2014-07-14 09:53:11

2
读取服务器上的JSON对象
html 
<input id="getReport" type="button" value="Save report" /> 

js 
(function($) { 
    $(document).ready(function() { 
     $('#getReport').click(function(e) { 
      e.preventDefault(); 
      window.location = 'pathtohandler/reporthandler.ashx?from={0}&to={1}'.f('01.01.0001', '30.30.3030'); 
     }); 
    }); 

    // string format, like C# 
    String.prototype.format = String.prototype.f = function() { 
     var str = this; 
     for (var i = 0; i < arguments.length; i++) { 
      var reg = new RegExp('\\{' + i + '\\}', 'gm'); 
      str = str.replace(reg, arguments[i]); 
     } 
     return str; 
    }; 
})(jQuery); 

c# 
public class ReportHandler : IHttpHandler 
{ 
    private const string ReportTemplateName = "report_template.xlsx"; 
    private const string ReportName = "report.xlsx"; 

    public void ProcessRequest(HttpContext context) 
    { 
     using (var slDocument = new SLDocument(string.Format("{0}/{1}", HttpContext.Current.Server.MapPath("~"), ReportTemplateName))) 
     { 
      context.Response.Clear(); 
      context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
      context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", ReportName)); 

      try 
      { 
       DateTime from; 
       if (!DateTime.TryParse(context.Request.Params["from"], out from)) 
        throw new Exception(); 

       DateTime to; 
       if (!DateTime.TryParse(context.Request.Params["to"], out to)) 
        throw new Exception(); 

       ReportService.FillReport(slDocument, from, to); 

       slDocument.SaveAs(context.Response.OutputStream); 
      } 
      catch (Exception ex) 
      { 
       throw new Exception(ex.Message); 
      } 
      finally 
      { 
       context.Response.End(); 
      } 
     } 
    } 

    public bool IsReusable { get { return false; } } 
}