【问题标题】:Spring MVC AJAX with Jquery cannot Retrieve json response带有 Jquery 的 Spring MVC AJAX 无法检索 json 响应
【发布时间】:2015-05-25 02:47:08
【问题描述】:

我想通过 ajax 搜索一个帐户。我的客户端有这个。

<form id="fetchAccount">
    <input type="search" name="id"/>
    <input type="submit"/>
</form>

<script>
    $(document).ready(function(){
        $('#fetchAccount').on('submit', function(e){

            var data = $(this).serialize();
            var header = $("meta[name='_csrf_header']").attr("content");
            var token = $("meta[name='_csrf']").attr("content");

            $.ajax({
                data:data,
                type:"PUT",
                url:"fetchAccout",
                dataType : 'json',
                contentType : 'application/json; charset=utf-8',
                beforeSend: function(xhr){
                    xhr.setRequestHeader(header, token);
                },
                success: function(response){
                    console.log(response);
                }
            });
            e.preventDefault();
        });
    });
</script>

在控制器上

@RequestMapping(value="/fetchAccout", method=RequestMethod.PUT,
                produces= MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Account fetchAccount(@RequestParam(value="id", required=false) Long id){
    Account account = null;
    if(id != null)
        account = custService.findAccountById(id);
    return account;
}

我有一个 200 HTTP 响应。我怀疑我的错误是在客户端。我什至无法在成功功能中发出警报。

【问题讨论】:

    标签: jquery ajax spring


    【解决方案1】:

    您的返回类型是 200,这意味着成功,但我可以看到您的控制器方法存在问题。您期望返回一个字符串,但实际上是返回帐户,将其更改为关注并尝试它。

    @RequestMapping(value="/fetchAccout", method=RequestMethod.PUT,
                    produces= MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Account fetchAccount(@RequestParam(value="id", required=false) Long id){
        Account account = null;
        if(id != null)
            account = custService.findAccountById(id);
        return account;
    }
    

    这将返回一个帐户对象。 然后更改您的控制台输出以返回一个 Account 参数,例如如果它有数字,那么让它这样做:

    console.log(response.number);
    

    【讨论】:

    • 哦抱歉错字。我实际上正在这样做,但我仍然看不到响应对象..
    • 你检查过 findAccountById 是否真的返回任何东西吗?您的 id 实际上返回 null 吗?我会取出 if(id != null) 行并测试它。
    • 哦,我发现我在 requestparam 中检索到的 id 为空。
    • 好的,一旦你修复了你的 id 为空,那么我发布的代码对你来说就可以了。将您的 id 输入字段更改为 这将是一个修复,并将限制用户仅输入数字
    • 虽然我尝试输入数字,但 id 仍然为空
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多