0

我正在尝试通过 AJAX 将 JSON 对象发布到 servlet。但是,该对象在 servlet 中为空。我无法弄清楚这段代码有什么问题。

JAVASCRIPT

function submitValues(event, val1, val2) 
{    
var xmlHttpObj = new XMLHttpRequest();                
            if(window.XMLHttpRequest) 
            {
                xmlHttpObj = new XMLHttpRequest();                    
             }
            else if(window.ActiveXObject)
            {
                xmlHttpObj = new ActiveXObject("Microsoft.XMLHttp");

            }


     var jsonObject =  submitTheValues(event, val1, val2);
       alert("json is:" +jsonObject);
     var json = JSON.stringify(jsonObject);
       alert("json after stringify:" +json);

        xmlHttpObj.open("POST", "../myapp/myservlet", true);
        xmlHttpObj.setRequestHeader("Content-type", "application/json");                    
        xmlHttpObj.send(json);

}  

伺服器

String jsonObj = request.getParameter("json");
4

1 回答 1

1

如果您想将数据作为参数接收,则必须将其发送为application/x-www-form-urlencode.

xmlHttpObj.open("POST", "../myapp/myservlet", true);
xmlHttpObj.setRequestHeader("Content-type", "application/x-www-form-urlencode");                    
xmlHttpObj.send('json='+encodeURIComponent(json));
于 2013-03-12T18:33:36.857 回答