Spring:在ajax请求之后获取表单对象

时间:2016-12-14 17:10:05

标签: ajax spring forms

我尝试使用Spring以ajax方式提交表单。我的代码是:

FilterForm是一个带有getter / setter的简单Bean。

@Controller
@RequestMapping("/mypage")
public class MyPageController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
        model.addAttribute("filterForm", new FilterForm());
        return "configuration/home";
     }

    @RequestMapping(value = "/filter", method = RequestMethod.POST)
    public String filter(@ModelAttribute FilterForm filterForm, Model model) {
        model.addAttribute("filterForm", filterForm);
        return "fragments/configuration/filter-result";
    }
}

查看home.html是:

        <form action="#" th:action="@{/mypage/filter}" th:object="${filterForm}" method="post" id="filterForm">
            <p>Field : <input type="text" th:field="*{field}" /></p>
            <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
        </form>

        <div id="filterResults"></div>

视图过滤结果(现在):

<span th:text="${filterForm.getField()}"></span>

只有这样,它才能正常工作。但它不是ajax。要以ajax方式提交表单,请使用:

$("#filterForm").submit(function(e) {
        e.preventDefault();
        var frm = $(this);
        $.ajax({
            contentType : 'application/json; charset=utf-8',
            type: frm.attr('method'),
            url: frm.attr('action'),
            dataType : 'html',
            data : frm.serialize(),
            success : function(callback){
                $("#filterResults").html(callback);
            },
            error : function(e){
                console.log('error');
                console.log(e.status + ' ' + e.statusText);
            }
        });
    });

在这种情况下,filter方法中filterForm的属性为null。在萤火虫中,我可以看到POST params形成良好,即“field = anything”。无法解释为什么Spring在ajax时无法将请求绑定到filterForm?

1 个答案:

答案 0 :(得分:0)

摆脱这一行contentType:application/json; charset=utf-8