我的 ajax
调用如下:
var x = document.forms["myForm"]["param1"].value;
var y = document.forms["myForm"]["param2"].value;
$.ajax({
url: "./webapi/user/get?param1="+x+'¶m2='+y,
contentType: 'application/json',
type: "GET",
data:{get_param:'value'},
success:function(data)
{
alert(data);
}
error:function(x,y,z){
alert(x+" "+y+" "+z);
}
});
我在 UserService
class
中有我的 java
函数,如下所示:
public int getFlag(String p_param1,String p_param2) {
int flag=0;
try{
dcc.connectionCall();
stmt=dcc.con.prepareCall("{? = call function1(?,?)}");
stmt.registerOutParameter(1,OracleTypes.INTEGER);
stmt.setString(2, p_param1);
stmt.setString(3, p_param2);
stmt.execute();
flag = stmt.getInt(1);
System.out.println("FLAG = "+flag+" "+p_param1+" "+p_param2);
}
catch(SQLException e){
e.printStackTrace();
}
return flag;
}
我的 UserResource
class
具有以下功能:
userService userservice = new UserService();
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public int getUser(@QueryParam("param1") String p_param1,@QueryParam("param2") String p_param2) throws SQLException{
int flag = userservice.getUserFlag(p_param1,p_param2);
System.out.println("FLAG= "+flag+" "+p_param1+" "+p_param2);
return flag;
}
上面的内容在 Eclipse 控制台上给出了正确的输出。但是,我无法在 ajax
call
中获得响应,这只是标志。我怎样才能得到它?我搜索了很多,但一切都像是获取 Object 作为响应并在那里将其字符串化
。但我不需要整个 json
。我只需要旗帜。对此的任何帮助都非常感激。我使用 Tomcat
作为服务器,上面的分配适用于 ConnectionPooling
和 RESTful
Web 服务。
最佳答案
使用$.parseJSON(data)
并得到你想要的。或者您必须将返回类型更改为明文(在服务器端),这似乎不可行。
@Altinak 是对的,指的是 jquery.ajax文档:
Different types of response to $.ajax() call are subjected to different kinds of pre-processing before being passed to the success handler. The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the dataType option. If the dataType option is provided, the Content-Type header of the response will be disregarded.
关于java - 如何在ajax成功函数中从java获取单值响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33735610/