简体   繁体   中英

Making AJAX POST request to Servlet fails

From my client side code, I am making an AJAX call to my servlet. If I use GET as request method. Everything works and I get response back. But when I send request as POST, servlet fails to send the response. From log I found out that in servlet "request" object is null when made ajax call with POST. According to this post: Servlet response to AJAX request is empty , I'm setting headers for same-origin policy.

Below is my code for reference:

function aimslc_ajaxCall(url,callback, postParams){
  var xmlhttp = null
  if (window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
  }
  xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
    eval( callback+"("+xmlhttp.responseText+")" );
    }
  }

  if(postParams!=null && typeof postParams!="undefined" ){
            xmlhttp.open("POST",url,true);
    xmlhttp.send(postParams);
  }else{
            xmlhttp.open("GET",url,true);
        xmlhttp.send();
  }
}

Servlet Code:

 public void doProcess (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      logger.info("doProcess::start..."+request.getQueryString());
      response.setHeader("P3P","CP='NOI ADM DEV PSAi COM NAV OUR OTR STP IND DEM'");
  response.setHeader("Access-Control-Allow-Origin","*");
  response.setHeader("Access-Control-Allow-Credentials","true");
  response.setHeader("Access-Control-Allow-Methods","POST, GET");
 }

Throws a null exception on request.getQueryString()

if you do a post all the data is in the request body, not on the url. From here you see that getQueryString only gets the stuff on the url.

See here for how to get the request body.

Also, if your data is name/value pairs, you might want to use getParameter and associated methods.

If the request is null, I ask do you implement doPost on your servlet?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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