request.getParameter()在用于AJAX调用时返回null

时间:2013-02-04 06:36:23

标签: ajax jsp xmlhttprequest request

我正在使用AJAX调用调用jsp:

        var httpRequest = null;
        if (window.XMLHttpRequest) {
            httpRequest = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (!httpRequest) {
            console.error('Cannot create an XML HTTP instance');
            return false;
        }
        httpRequest.onreadystatechange = function() {
            try {
                if(httpRequest.readyState === 4) {
                    ...
                }
            } catch(e) {
                args.error(e);
            }
        };
        httpRequest.open(args.method, args.path, args.sync);
        httpRequest.setRequestHeader(...);
        var q = '', first = true;
        for(var key in args.params) {
            if(params.hasOwnProperty(key)) {
                if(first) {
                    first = false;
                } else {
                    q += '&';
                }
                q += encodeURIComponent(key) + '=' + encodeURIComponent(args.params[key]);
            }
        }
        httpRequest.send(q);

对于此请求,我将查询参数传递为:

{
    from: 'xyz',
    to: 'abc'
}

正在构建的查询也是正确的:

from=xyz&to=abc

在我的JSP上,当我request.getParameter("from")时,我得到null。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

找到解决方案:

缺少标题: httpRequest.setRequestHeader(' Content-Type',' application / x-www-form-urlencoded');

这对于帖子requests是必要的。