【问题标题】:How to submit spring form in ajax(jquery) with modelAttribute如何使用modelAttribute在ajax(jquery)中提交spring表单
【发布时间】:2012-12-07 02:41:11
【问题描述】:

我是 Spring MVC 的新手。 我有这样的表格,

<form:form action="/myaction.htm" method="post" modelAttribute="myForm" id="formid"> 和一个返回 json 的控制器

public @ResponseBody ResultObject doPost(@ModelAttribute("myForm") MyForm myForm){ System.out.println("myform.input"); }

我可以使用$("#formid").submit(); 提交此内容,并且我的 modelAttribute 工作正常,从 UI 中获取值。

我的问题是,如何以 jquery ajax 方式提交此表单? 我试过了,

$.ajax({
type:"post",
url:"/myaction.htm",
async: false,
dataType: "json",
success: function(){
alert("success");
}

});

表单已提交,但modelAttribute值为null,如何在提交时包含modelAttribute对象(表单正在使用的对象)?

【问题讨论】:

    标签: java jquery spring jsp


    【解决方案1】:

    您需要发布数据。我通常这样做的方式是使用以下内容。

    var str = $("#myForm").serialize();
    
    $.ajax({
        type:"post",
        data:str,
        url:"/myaction.htm",
        async: false,
        dataType: "json",
        success: function(){
           alert("success");
        }
    });
    

    【讨论】:

    • 我正在使用带有 CSRF 的 SpringSecurity,我得到了这个:无法识别的令牌 '_csrf':期待('true'、'false' 或 'null')。有什么解决办法吗?
    • @zygimantus,您需要将操作链接 url 添加到 cSRF 过滤器,否则它不会通过。
    • 好的,但是如果我想使用 restful 编程,因此为了更新我需要使用 PUT 方法。在这种情况下,我们怎样才能让它发挥作用?
    【解决方案2】:

    您的 ModelAttributes 未填充,因为您没有将任何参数传递给服务器。表单数据必须发布到服务器

    $.post('myaction.htm', $('#formid').serialize())发送ajax post请求。

    【讨论】:

      猜你喜欢
      • 2012-08-12
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多