java - 如何在ajax成功函数中从java获取单值响应

标签 java ajax rest

我的 ajax 调用如下:

var x = document.forms["myForm"]["param1"].value;
var y = document.forms["myForm"]["param2"].value;
$.ajax({
        url: "./webapi/user/get?param1="+x+'&param2='+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 作为服务器,上面的分配适用于 ConnectionPoolingRESTful 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/

相关文章:

java - RestTemplate:如何一起发送 URL 和查询参数

python - 如何在生产中调试ajax View ?

php - 在屏幕上打印响应标题的消息

java - 在 Spring Boot 中从生成 PDF 内容类型内容的外部 Rest API 中提取响应字节的正确方法是什么?

Java:懒加载单例和反射攻击?

Java 多重扫描器

javascript - jquery 数据表 : how to shift columns mappings (because of inserted "row header column")?

java - 无法测试 Restful Web 服务

java - Jackson 功能 ACCEPT_SINGLE_VALUE_AS_ARRAY 不适用于注释

java - 将 Android 应用程序嵌入到其他 Android 应用程序中(Overlay + Events)