2010-06-01 93 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; } } 
}