简体   繁体   中英

How to get a single value response from java in an ajax success function

I have my ajax call like this:

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);
        }
    });

I have my java function in UserService class is written like this:

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;
}

I have my UserResource class with the following function:

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;
}

The above thing gives proper output on eclipse console. However I am unable to get the response in ajax call , which is nothing but the flag. How do I get it? I searched a lot but everything is like getting Object as a response and get it stringified there. But entire json is not needed to me. I just need the flag. Any help upon this much appreciated. I am using Tomcat as a server and the above assignment is for ConnectionPooling with RESTful web service.

Use $.parseJSON(data) and get what you want. Or you will have to change your return type to cleartext (at your server-side) which does not seem feasible.

@Altinak is right, referring to jquery.ajax documentation:

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.

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