简体   繁体   English

Ajax调用spring控制器回调错误函数

[英]Ajax call to spring controller callback error function

Can you tell me what it's going wrong with the following ajax call to controller ? 您能告诉我以下对控制器的ajax调用出了什么问题吗?
The controller that is called via ajax : 通过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 : ajax函数:

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 jqxhr.responseText is always the value returned by the controller(in this case 'success' or 'failure'. 现在,当我执行对控制器的ajax调用时,它将始终执行错误功能,并且jqxhr.responseText始终是控制器返回的值(在这种情况下为“成功”或“失败”。

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. 如果我将控制器返回的值更改为“ true”或“ false”,则ajax将成功回调“成功”功能。
I also tried with produces="application/json" and got the same result. 我还尝试了produces="application/json"并得到了相同的结果。

Change the datatype to: datatype更改为:

 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-----------------------------------^^^^^^^^^^^^^^^^^^^^^^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM