我已经通过几乎所有关于此问题的Stack溢出答案来解决这个问题,我尝试了很多东西,但是我仍然得到null,我只是想尝试使用AJAX从一个java脚本变量发送到servlet JS中的else
语句如下所示,并且我在警告框中获得null
:
else { //begin JS else
var somevar="iam the user";
$.ajax({
type:"POST",
url:"Register",
dataType: 'json',
contentType:'application/json',
data:{
Subject:somevar},
cache: false,
processData:false,
success: function(data){
alert(data);
},
error: function(){
alert("error");
}
});
} //end else
我的servlet中的doPost方法(注册)
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
resp.setCharacterEncoding("UTF-8");
String user = req.getParameter("Subject");
//resp.sendRedirect("registration.jsp");
PrintWriter out = resp.getWriter();
out.println(user);
//String pathInfo = req.getRequestURI();
}
我尝试了很多不同的东西,但仅举几例:
1 - 如果我取消注释并使用此行并评论其他行:resp.sendRedirect("registration.jsp");
然后我在警告框中得到error
作为回复。
2 - 如果我将另一个字符串(不是用户值)从servlet发送回ajax作为响应,例如:out.println("some string");
然后我在JS警告框中得到那个字符串就好了
我尝试过的其他事情,很明显这个值是从ajax成功发送到servlet的,但是当服务器读取它时,它是null,服务器可以将字符串响应发送回ajax(除了以外的任何变量) <{1}}值和ajax就好了。
鉴于此,我尝试使用答案such as this answer执行一些处理步骤(在servlet上提取JSON元素)。但在我尝试这个答案后,警告框再次给出了getparameter()
。
我知道还有其他方法可以使用http(例如send()方法)发送数据,但我发现ajax只是因为iam发送多个数据对象而不仅仅是一个(在我的例子中它只有一个,但我会用它来发送多个数据元素)。 任何帮助将不胜感激。
更新:取得了一些进展,通过查看更多答案,例如this one,我可以修改答案和代码并将它们组合在一起,同时借助@ stdunbar关于浏览器调试的评论极其有用,我能够在浏览器中跟踪内容,现在问题几乎已经解决但不完全,现在我可以从请求中提取值并将其转换为字符串,但是当我将字符串发送回ajax(js)时,警报框显示error
,但好消息是,浏览器调试器将respose显示为字符串,但是alertbox无法显示它,这是我的更新的servlet代码:
(error)
我的AJAX:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter out = resp.getWriter();
StringBuilder sb = new StringBuilder();
BufferedReader br = req.getReader();
String str;
while( (str = br.readLine()) != null ){
sb.append(str);
}
try{
JSONObject jObj = new JSONObject(sb.toString());
String extracted=jObj.getString("Subject").toString();
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
// resp.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
// resp.setCharacterEncoding("UTF-8");
out.println(jObj);
}catch (JSONException e) {
}
}
答案 0 :(得分:0)
所以在我发布的更新后,我进一步研究并最终解决了它,问题是内容类型是在servlet和JS / ajax(这是正确的)中设置application / json,但我是期望在警告框中弹出一个字符串,所以除了servlet中更新的代码之外,我在ajax中更改了这一行:
发件人强>
alert(data); // this line trying to get the json object (wrong)
致
alert(data.Subject); // this line is getting the value of the key (correct)
感谢所有的回复和评论,他们都帮了忙。