简体   繁体   English

AJAX 未收到来自 servlet 的响应

[英]AJAX not receiving response from servlet

I have an AJAX making a POST to a servlet.我有一个 AJAX 向 servlet 发送 POST。 Servlet does some computation and returns a response. Servlet 进行一些计算并返回响应。 AJAX success function reads the response and does certain things. AJAX 成功函数读取响应并执行某些操作。

AJAX CALL AJAX 调用

$.ajax( {
     type: "POST",
     url: "/bin/path/to/Servlet",
     data: $(this).serialize(),
     dataType: "html",
     success: function(responseValue) {
         if(responseValue == '200') {
              // Do something
          }else {
              console.log("it is not 200");
          }
     },
     error: trialForm.trialError
     }).done(function(status) {
             $(trialForm.submitButton).show();
             $(trialForm.loader).hide();
     });
}

SERVLET SERVLET

protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {
     response.setContentType("text/html");    

     URL url = new URL("www.apriurl.com");
     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
     conn.setDoOutput(true);
     conn.setRequestMethod("POST");
     conn.setRequestProperty("Content-Type","application/json");
     conn.setRequestProperty("Authorization","XXXXZZZZ " + strSig);
     conn.setRequestProperty("Accept","application/json");
     conn.setRequestProperty("ZZZZZ",clientID);

     OutputStream os = conn.getOutputStream();
     os.write(inputParameters.getBytes());
     os.flush(); 

     System.out.println(conn.getResponseCode());
     response.getWriter().write(conn.getResponseCode());
}
  • responseValue is a variable used in teh java class. responseValue 是 java 类中使用的变量。
  • It has the right value.它具有正确的价值。 I see the value being print in log file after sys out executed在 sys out 执行后,我看到在日志文件中打印的值
  • The response is just a garbled question mark (?).响应只是一个乱码的问号 (?)。 I console logged it.我控制台记录了它。 I am guessing it has to do something with the data type.我猜它必须对数据类型做些什么。 I tried a few other types but couldn;t figure out.我尝试了其他几种类型,但无法弄清楚。 Any help is appreicated.任何帮助表示赞赏。

This is doing a write (int) rather than a write (String) so if you do write(200) it is sending the ascii value of 200这是write (int)而不是write (String)所以如果你write(200)它发送的ascii值200

try sending 200 as a String尝试将200作为字符串发送

as作为

response.getWriter().write(String.valueOf (conn.getResponseCode()));

see https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#write(int)https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#write(int)

public void write(int c)公共无效写(int c)

Writes a single character.写入单个字符。

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

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