用ASP.NET处理xhr

时间:2012-09-06 18:04:04

标签: asp.net ajax post xmlhttprequest

我想从客户端(JavaScript)异步发送POST到服务器端(ASP.Net),带有2个参数:numeric和long formated string。

我理解长格式字符串必须有encodeURIComponent()才能传递它。

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

拜托,你能帮助我吗?我用ajax,xhr,Request.QueryString [],Request.Form [],......搞错了。

1 个答案:

答案 0 :(得分: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" />