Handle xhr with ASP.NET

别来无恙 提交于 2020-01-07 04:17:28

问题


I would like to send a POST asynchronously from client side (JavaScript) to server side (ASP.Net) with 2 parameters: numeric and long formated string.

I understand the long formated string must have encodeURIComponent() on it befor passing it.

My trouble is I want to embed the long encoded string in body request and later open it from C# on server side.

Please, can you help me? I'm messing too much with ajax, xhr, Request.QueryString[], Request.Form[], ....


回答1:


First, create an HTTPHandler:

using System.Web;
public class HelloWorldHandler : IHttpHandler
{
    public HelloWorldHandler()
    {
    }
    public void ProcessRequest(HttpContext context)
    {
        HttpRequest Request = context.Request;
        HttpResponse Response = context.Response;
        //access the post params here as so:
        string id= Request.Params["ID"];
        string longString = Request.Params["LongString"];
    }
    public bool IsReusable
    {
        // To enable pooling, return true here.
        // This keeps the handler in memory.
        get { return false; }
    }
}

Then register it:

<configuration>
    <system.web>
        <httpHandlers>
            <add verb="*" path="*.ashx" 
                  type="HelloWorldHandler"/>
        </httpHandlers>
    </system.web>
</configuration>

Now call it - using jQuery Ajax:

$.ajax({
      type : "POST",
      url : "HelloWorldHandler.ashx",
      data : {id: "1" , LongString: "Say Hello"},
      success : function(data){
             //handle success
      }
 });

NOTE

Totally untested code but it should be very close to what you need.

I just tested and it works out of the box. This is how I called it:

<script language="javascript" type="text/javascript">
    function ajax() {
        $.ajax({
            type: "POST",
            url: "HelloWorldHandler.ashx",
            data: { id: "1", LongString: "Say Hello" },
            success: function (data) {
                //handle success
            }
        });
    }
</script>
<input type="button" id="da" onclick="ajax();" value="Click" />


来源:https://stackoverflow.com/questions/12305867/handle-xhr-with-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!