简体   繁体   English

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

[英]Unable to POST JSON object from Javascript to a Servlet via AJAX

I am trying to POST a JSON object to a servlet via AJAX. 我试图通过AJAX将JSON对象发布到Servlet。 However, the object is null in the servlet. 但是,该对象在servlet中为null。 I am unable to figure out what's wrong with this code. 我无法弄清楚这段代码出了什么问题。

JAVASCRIPT 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 SERVLET

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

If you want to receive the data as a parameter you'll have to send it as application/x-www-form-urlencode . 如果要接收数据作为参数,则必须将其作为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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM