无法通过AJAX将JSON对象从Javascript发布到Servlet

时间:2013-03-12 18:28:20

标签: javascript ajax json servlets post

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

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);

}  

SERVLET

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

1 个答案:

答案 0 :(得分: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));