使用Jquery的Ajax函数返回400错误

时间:2016-06-20 09:17:18

标签: javascript java jquery ajax spring

我正在Jquery使用Spring MVC

我有index.jsp

<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
    integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
    crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
    integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
    crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script
    src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"
    integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS"
    crossorigin="anonymous">

</script>

<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
    <script type="text/javascript">
</script>
<script>
    $(document).ready(function() {
        $("input").keyup(function() {
            $.ajax({
                url : "myController",
                type: "POST",
                data: $("#name").val(),
                success : function(result) {

                    alert(result);
                }

            });
        });
    });
</script>

</head>

<body>

    <form>
        <div class="row">
            <div class="col-sm-12">
                <label for="name">Name:</label>
            </div>
            <div class="col-sm-1">
                <input type="text" class="form-name" id="name" placeholder="Paolo">
            </div>
        </div>
    </form>
</body>
</html>

正如您在输入框中插入字母时所看到的,我使用jQuery运行$ajax。 我的HTTP POST请求是已发送的,但我有400错误。

这是我简单的Controller类:

    @Controller
public class MyController {


    @RequestMapping(value="/myController", method = RequestMethod.POST)

    @ResponseBody
    public String getData(@RequestParam(value="name") String name) {

        return name;    
    }
}

我的Spring MVC的DispatcherServlet是相关的。 我怎么解决?

1 个答案:

答案 0 :(得分:1)

A 400表示请求格式错误。换句话说,客户端发送到服务器的数据流不遵守规则。

你的ajax电话会是

$.ajax({
        url : "myController",
        type: "POST",
        data:{"name": $("#name").val()},
        success : function(result) {                       
                 alert(result);
               }

       });