【问题标题】:Handle xhr with ASP.NET使用 ASP.NET 处理 xhr
【发布时间】:2012-08-31 14:45:30
【问题描述】:

我想使用 2 个参数从客户端 (JavaScript) 异步发送 POST 到服务器端 (ASP.Net):数字和长格式字符串。

我知道长格式的字符串在传递之前必须有 encodeURIComponent()。

我的麻烦是我想在正文请求中嵌入长编码字符串,然后在服务器端从 C# 打开它。

拜托,你能帮帮我吗?我对 ajax、xhr、Request.QueryString[]、Request.Form[]、....

【问题讨论】:

    标签: asp.net ajax post xmlhttprequest


    【解决方案1】:

    首先,创建一个 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; }
        }
    }
    

    然后注册:

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

    现在调用它 - 使用 jQuery Ajax:

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

    注意

    完全未经测试的代码,但它应该非常接近您的需要。

    我刚刚测试过,它开箱即用。我是这样称呼它的:

    <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" />
    

    【讨论】:

    • 这样,传递给 Post ajax 调用的数据会嵌入到请求正文中吗? (而不是进入 ajax 调用的查询字符串?)
    猜你喜欢
    • 2011-08-15
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 2015-08-01
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 2019-07-16
    相关资源
    最近更新 更多