首页 > 解决方案 > Spring MVC @ModelAttribute 未填充 AJAX Post 请求

问题描述

当我尝试使用 Ajax Post 请求将数据发送到我的控制器时,我的 @ModelAttribute 对象不会被填充。但是当我使用表单提交发送值时,它工作正常。请检查下面的代码,

形式,

<form action="#" id="productForm" th:action="@{/save}" th:object="${product}" method="POST">
    <table>
        <tbody>
            <tr>
                <td>Name:</td>
                <td><input id="name" type="text" th:field="*{name}" /></td>
            </tr>
            <tr>
                <td>Brand:</td>
                <td><input id="brand" type="text" th:field="*{brand}" /></td>
            </tr>
            <tr>
                <td>Made In:</td>
                <td><input id="madeIn" type="text" th:field="*{madeIn}" /></td>
            </tr>
            <tr>
                <td>Price:</td>
                <td><input id="price" type="text" th:field="*{price}" /></td>
            </tr>
        </tbody>
    </table>
    <br />
    <button type="submit">Save</button>
    <button type="button" onclick="saveWithAjaxPost();">Save with Ajax Post</button>
</form>

控制器,

@RequestMapping(value = "/saveWithAjaxPost", method = RequestMethod.POST)
@ResponseBody
public ModelMap saveWithAjaxPost(@ModelAttribute Product product) {
    ModelMap model = new ModelMap();
    service.saveProduct(product);
    model.put("MESSAGE", "Success");
    return model;
}

JavaScript,

function saveWithAjaxPost(){

    var params = $("#productForm").serialize();

    $.ajax({

        url:"/saveWithAjaxPost",
        type:"POST",
        contentType:"application/json",
        data:params,
        async:true,
        dataType:"json",
        success:function(response){
            $('#productsListDiv').empty();
            getAllProcucts();
        },
        error:function(response){
            alert(response.message);
        }
    });
}

"name=test_name&brand=test_brand&madeIn=test_made_in&price=1000"在序列化表格后得到。

这是我的控制器在运行代码时得到的, 在此处输入图像描述

这一定是一个非常简单的错误,但我无法弄清楚我在这里做错了什么......可能是什么问题?

标签: javaajaxspringspring-mvc

解决方案


推荐阅读