ASP.NET - Passing JSON from jQuery to ASHX

前端 未结 8 490
你的背包
你的背包 2020-11-28 21:25

I\'m trying to pass JSON from jQuery to a .ASHX file. Example of the jQuery below:

$.ajax({
      type: \"POST\",
      url: \"/test.ashx\",
      data: \"{\         


        
相关标签:
8条回答
  • 2020-11-28 22:05

    The following solution worked for me:

    Client Side:

            $.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);
                }
            });
    

    Server Side .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 讨论(0)
  • 2020-11-28 22:05

    This works for calling web services. Not sure about .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 讨论(0)
提交回复
热议问题