jQuery方法无法将数据传递到REST服务器

时间:2019-03-31 07:49:44

标签: javascript jquery spring-restcontroller

这些代码是关于jQuery JavaScript的,可将数据传递到Spring Boot的RESTful服务器。首先,以下代码是Rest Controller的来源。

@RestController
@RequestMapping(value="/rest/user")
public class UserRestController {

    @Autowired
    private UserService userService;

    @PostMapping("login")
    public ResponseEntity<Boolean> authenticated(@RequestBody User user) {

        System.out.println(user.getUsername() + user.getPassword()); // return values are NULL

        Boolean blogin = userService.authenticate(user.getUsername(), user.getPassword());
        if(!blogin)
            return new ResponseEntity<Boolean>(blogin, HttpStatus.NOT_ACCEPTABLE);

        return new ResponseEntity<Boolean>(blogin, HttpStatus.OK);
    }
}

还有jQuery JavaScript代码。

== index.html ==

<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="/js/ajaxlogin.js"></script>
</head>
<body>
    <h1>Please sign in</h1>
    <form method="post" id="loginForm" th:object="${loginForm}">
        <div><label for="username">username</label></div>
        <input id="username" type="text" name="username" th:value="*{username}"/>

        <div><label for="password" th:value="*{username}">password</label></div>
        <input id="password" type="password" name="password" th:value="*{password}" />

        <div>
            <input type="submit" value="Login" />
            <a href="index.html" th:href="@{/posts}">Cancel</a>
        </div>
    </form>
    <div id=helloUserDiv></div>
</body>
</html>

== ajaxlogin.js ==

$(document).ready(function () {

    $("#loginForm").submit(function (event) {

        //stop submit the form, we will post it manually.
        event.preventDefault();
        ajax_login_submit();
    });
});

function ajax_login_submit() {

    var user = {
        username : $("#username").val,
        password : $("#password").val
    }

    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "rest/user/login/",
        data: JSON.stringify(user),
        dataType: 'json',
        cache: false,
        timeout: 600000,
        success: function (data) {

            var resultJson = JSON.stringify(data);
            $('#helloUserDiv').html(resultJson);
            console.log("SUCCESS : ", data);
            alert(data);

        },
        error: function (e) {

            var resultJson = e.responseText;
            $('#helloUserDiv').html(resultJson);
            console.log("ERROR : ", e);
        }
    });
}

但是结果失败。错误代码406。我不确定这些代码有什么错误。

已更新

我如下修改了JavaScript,

function ajax_login_submit() {

    var user = {
            username: $("#username").val(),
            password: $("#password").val()
        };

    console.log(user.username);
    console.log(user.password);
    console.log(user);

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "rest/user/login",
        data: JSON.stringify(user),
        //dataType: 'json',
        success: function (data) {

            var resultJson = JSON.stringify(data);
            $('#helloUserDiv').html(resultJson);
            console.log("SUCCESS : ", data);
            alert(data);

        },
        error: function (e) {

            var resultJson = e.responseText;
            $('#helloUserDiv').html(resultJson);
            console.log("ERROR : ", e);
        }
    });
}

console.log(user)返回以下正确的值,

{用户名:“ joseph”,密码:“ password”}

但是RestController带来了一些问题。

@RestController
@RequestMapping(value="/rest/user")
public class UserRestController {

    @Autowired
    private UserService userService;

    @PostMapping("login")
    public ResponseEntity<Boolean> authenticated(@RequestBody User user) {

        System.out.println(user.getUsername() + user.getPassword()); // return values are "josephnull"

        Boolean blogin = userService.authenticate(user.getUsername(), user.getPassword());

System.out.println(user.getUsername() + user.getPassword());此行返回“ josephnull”,即密码为空。我不明白为什么密码值是空的。

3 个答案:

答案 0 :(得分:1)

错误代码406表示该数据不可接受。这是详细信息。 https://github.com/SubhashPatel/Install-Zimbra-mail-server-ubuntu/blob/master/configure-ssl-zimbra.sh 从您的代码中删除dataType: 'json',它将起作用。有了这一行,代码一经删除就抛出parse error,错误消失了,响应成功了。

这是工作代码,请忽略我使用的url

$.ajax({
        type: "POST",
        contentType: "application/json",
        url: "hms/raw/login",
        data: JSON.stringify(user),

        cache: false,
        timeout: 600000,
        success: function (data) {

            var resultJson = JSON.stringify(data);
            $('#helloUserDiv').html(resultJson);
            console.log("SUCCESS : ", data);
            alert(data);

        },
        error: function (e) {

            var resultJson = e.responseText;
            $('#helloUserDiv').html(resultJson);
            console.log("ERROR : ", e);
            console.log(JSON.stringify(e));
        }
    });

答案 1 :(得分:0)

在您的jquery $ .ajax调用中,尝试放入

data: {user :JSON.stringify(user)},而不是data: JSON.stringify(user) ,data: {user : user},根据您的需要 然后代码将是:

function ajax_login_submit() {

        var user = {
            username : $("#username").val,
            password : $("#password").val
        }

        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "rest/user/login/",
            data: data: {user :JSON.stringify(user)},
            dataType: 'json',
            cache: false,
            timeout: 600000,
            success: function (data) {

                var resultJson = JSON.stringify(data);
                $('#helloUserDiv').html(resultJson);
                console.log("SUCCESS : ", data);
                alert(data);

            },
            error: function (e) {

                var resultJson = e.responseText;
                $('#helloUserDiv').html(resultJson);
                console.log("ERROR : ", e);
            }
        });
    }

答案 2 :(得分:0)

您可以使用FormData()发布数据,例如:

var data = new FormData();
data.set('key', 'value');

如果您要发送图片,则

data.append('image', imageFile);

然后设置标题headers: {'Content-Type': 'multipart/form-data'并发送它而不进行字符串化。

它应该像这样:

$.ajax({
     type: "POST",
     contentType: "multipart/form-data",
     url: "to/url",
     data: data,
     success: function (data) {
         alert(data);
     }
});