ASP.NET - Passing JSON from jQuery to ASHX

前端 未结 8 530
你的背包
你的背包 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;
               }
            }
        }
    

提交回复
热议问题