简体   繁体   中英

Ajax call to spring controller callback error function

Can you tell me what it's going wrong with the following ajax call to controller ?
The controller that is called via ajax :

@RequestMapping(value = "/userManagement/loadData.html", method = RequestMethod.POST,produces="text/plain")
public @ResponseBody String loadData(@RequestBody String jsonData) {
    try {
        Map<String, Object> data = JsonUtils.jsonAsMap(jsonData);
        pageSize = Integer.valueOf(data.get("pageSize").toString());
        pageNumber = Integer.valueOf(data.get("pageNumber").toString());
    } catch (Exception e) {
        return "failure";
    }
    return "success";
}

The ajax function :

function reloadUsers(){
    $.ajax({
        type : "POST",
        cache : false, 
        dataType: 'json',  
        contentType: 'application/json',
        mimeType: 'application/json',
        url : "userManagement/loadData.html",
        data : JSON.stringify({
            pageSize : 10,
            pageNumber : 0
        }),
        success : function(response) {
            if(response.responseText=='true'){
                console.log('success');
            }else{
                console.log('server error');
            }
        },
        error : function(jqxhr){
            console.log('error');
            console.log(jqxhr.responseText);
        } 
    });
}


Now when i execute the ajax call to the controller it always goes on the error function and the is always the value returned by the controller(in this case 'success' or 'failure'. 始终是控制器返回的值(在这种情况下为“成功”或“失败”。

My question is why is this happening ?
If i change the controller returned values to "true" or "false" the ajax successfully callback the 'success' function.
I also tried with produces="application/json" and got the same result.

Change the datatype to:

 dataType: 'text', 

As you are going to get a string in response because of this:

@RequestMapping(value = "/userManagement/loadData.html", ....... produces="text/plain")
                                            //--------because of this-----------------------------------^^^^^^^^^^^^^^^^^^^^^^

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