0

我已经阅读了这个这个以获得一些帮助,但是我的代码有问题。好吧,我想通过 Ajax 向数据库插入一个表单,这就是我所做的:

Ajax 函数:

<script type="text/javascript">
        function doAjaxPost() {

        var form = $('#ajf');
        frm.submit(function () {
        $.ajax({
        type: "POST",
        url: "${pageContext.request.contextPath}/ajouter_user",
        data:  form.serialize(),
        success: function(response){
        // we have the response
        $('#info').html(response);

        },
        error: function(e){
        alert('Error: ' + e);
        }
        });
        });
        }
        </script>

'#info' 是我要显示控制器返回的成功消息的 DIV 的 ID。

这是我的控制器:

@RequestMapping(value="/ajouter_user",method=RequestMethod.POST)
    public @ResponseBody String addUser(@ModelAttribute User us,BindingResult result,ModelMap model){
        String returnText;
        if(!result.hasErrors()){
            model.addAttribute("us", new User());
            userservice.AddUser(us);

            model.addAttribute("usersystem", userservice.getAllUsers());
           return returnText = "User has been added to the list." ;
        }else{
           return returnText = "Sorry, an error has occur. User has not been added to list.";
        }

    } 

HTML:

<form:form id="ajf" method="POST" commandName="user">
         Here are my fields ...
        <input  type="submit" value="Créer" onclick="doAjaxPost()"/>

</form:form>

问题是:我没有得到控制器返回的字符串,我得到一个警告错误(object [] object),数据被插入到数据库中,提交后页面重新加载而没有给出任何错误

有人可以给我一个如何在 spring 中使用 Ajax 的教程(插入数据库)请帮助我

4

1 回答 1

0

如果您使用的是 jQuery(看起来像),那么您需要在函数中包含事件并执行event.preventDefault()以防止表单提交。否则事件将向上传播,表单将提交,您将获得 ajax 帖子和表单帖子。

于 2013-06-04T19:02:52.610 回答