Ajax请求不适用于Spring控制器

时间:2014-08-27 21:58:28

标签: java javascript jquery ajax spring-mvc

无法理解为什么此代码始终在控制台"Error!"中打印。

这是我的Spring控制器

@RequestMapping("/spinner")
public class SpinnerController {

    @RequestMapping(method = RequestMethod.GET,
                    produces = "application/json")
    public @ResponseBody String spinner() throws InterruptedException {
        Thread.sleep(10);
        return "answer";
    }
}

我的JS脚本:

function sendRequest() {
    $.ajax({
            url: '/spinner',
            type: 'get',
            contentType: "application/json",
            success: function (resp) {
                alert("Yeah!");
                console.log(resp);
            },
            error: function (){
                console.log("Error!");
            }
        }
    );
}

和JSP页面:

<html>
<head>
    <link type="text/css" rel="stylesheet" href="../resources/css/style.css"/>
    <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/pure-min.css">
    <script type="text/javascript" charset="utf-8" src="../resources/js/jquery.js"></script>
    <script type="text/javascript" charset="utf-8" src="../resources/js/send.js"></script>
</head>
<body>
    <button class="pure-button pure-button-primary" onclick="sendRequest()">Press me!</button>
    <div id="spinner">Greeting!</div>
</body>
</html>

为什么我收到错误的任何想法?

UPD

这是脚本方法错误的日志

error: function (jqXHR, textStatus, errorThrown) {
    console.log(jqXHR);
    console.log(textStatus);
    console.log(errorThrown);
}

控制台输出:

[object Object] send.js:14
parsererror send.js:15
SyntaxError: Unexpected token a 

UPD2

修正了添加此代码:

@RequestMapping(method = RequestMethod.GET,
                produces = "application/json")
public @ResponseBody Answer spinner() throws InterruptedException {
    Thread.sleep(10);
    return new Answer("info");
}

public class Answer {    
    private String data;

    public Answer(String data) {
        this.data = data;
    }

    public Answer() {
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}

1 个答案:

答案 0 :(得分:2)

默认情况下,JQuery试图猜测使用MIME类型在XHR响应中会出现什么类型的数据。 Spring返回的数据与您发送的MIME类型不匹配。您可以将后端方法更改为:

@RequestMapping("/spinner")
public class SpinnerController {

@RequestMapping(method = RequestMethod.GET,
                produces = "application/json")
public @ResponseBody String spinner() throws InterruptedException {
    Thread.sleep(10);
    return "[{\"answer\":1}]";
}
}

你也可以强制jQuery不要查看MIME类型(不是一个好主意)并在你的ajax对象中设置dataType : 'text'