Request.Form POSTED变量为空

时间:2015-04-27 20:52:53

标签: c# .net ajax

我已经通过使用浏览器调试器/网络监视器验证了我在一个名为“search”的AJAX调用中的变量中发送,并且在监视器中它在标题中显示为“search = test”。我试图在后面的代码中访问此变量,但似乎无法找到它?这是我的前端和后端代码,我错过了什么?

代码背后:

public class AJAXSearchLog : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string searchTerm = Convert.ToString(HttpContext.Current.Request.Form["search"]);
        if(!string.IsNullOrEmpty(searchTerm)){
           AspDotNetStorefrontCore.DB.ExecuteSQL("insert into TribSearch(SearchTerm,CustomerID,LocaleSetting) values(" + DB.SQuote(CommonLogic.Ellipses(searchTerm, 97, true)) + "," + '0' + "," + DB.SQuote("en-us") + ")");
        }
        context.Response.Clear();
        context.Response.Write(searchTerm);
        context.Response.End();
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

前端

  window.onbeforeunload = function(e) {
        if ($("#searchBox_text").val().length >= 2) {
        var _search = $("#searchBox_text").val();
            var url = "/AJAXSearchLog.ashx";
            $.ajax({
                async: false,
                type: 'POST',
                url: url,
                data: {'search': _search},
                contentType: 'application/json;',
                dataType: 'json',
                success: function(result) {
                    alert(result);
                },
                error: function(xhr, textStatus, errorThrown) {
                    console.log('error');
                }
            });
        }
    };

1 个答案:

答案 0 :(得分:1)

我发现当contentType设置为' application / json'时,数据没有通过。另外,要读取POST变量,需要Request.Params[]。以下是我更改的两行代码:

在前端 - contentType: 'application/x-www-form-urlencoded; charset=UTF-8',

在后端 - string searchTerm = Convert.ToString(context.Request.Params["search"]);