Thymeleaf刷新页面随访 - 现在,随着AJAX [英] Thymeleaf page refresh followup - Now with AJAX

查看:6384
本文介绍了Thymeleaf刷新页面随访 - 现在,随着AJAX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为后续我刚才的问题,关于使用Thymeleaf和preventing刷新页面:

http://forum.thymeleaf.org/$p$pventing-page-refresh-Thymeleaf-amp-Spring-MVC-td4029155.html

基本上,我有一个工作的Spring MVC应用程序,使用Thymeleaf保存表单数据。当用户保存数据的页面将刷新(因为我想离开他们在页面上获得更多的编辑),我想消除页面刷新。

我有codeD了一些JavaScript使用jQuery阿贾克斯发布的数据,以我的Spring MVC控制器。诀窍似乎不使用一个提交按钮,只是一个普通的按钮和一个JS函数绑定到它的数据发送到服务器。

这一切似乎很好地工作,但我想确保我明白发生了什么。我特别想知道如果Thymeleaf现在是多余的。我不认为这是因为当我最初加载页面Thymeleaf仍然绑定到数据bean。从使用调试器在服务器端中的控制器,它看起来像后请求调用映射方法,并传递数据到模型

我会AP preciate你对这个是否是正确的方法评论做到这一点。

最后,我该如何处理错误,例如说仓库没有持续的数据以任何理由?

非常感谢。

下面是表单的重要部分:

 <表格ID =adminDataForm行动=#号:行动=@ {/ admin_ajax}日:对象=$ {adminFormAjax}的方法=后>


<输入类型=按钮值=保存更改ID =邮报的onClick =送出数据()/>
 

下面是JavaScript:

 功能送出数据()
{
        $阿贾克斯(
        {
            键入:POST,
            数据:$(#adminDataForm)序列化()。
            缓存:假的,
            网址:/ admin_ajax
            成功:函数(数据)
            {
                警报(您的修改已经保存);
            },
            错误:函数()
            {
                警报(错误 - 未保存的数据);
            }

        });
}
 

下面是控制器:

  @SessionAttributes(adminFormAjax)
@Controller
公共类的TestController
{
    最后的静态保护的长INDEX_RA = 2L;

    @Autowired
    私人AdminDataRepository代表;

    @RequestMapping(值=/ admin_ajax,方法= RequestMethod.GET)
    公共字符串adminFormAjax(型号机型)
    {
        AdminData广告= rep.findById(INDEX_RA);

        //如果没有配置记录,创建一个并指定主键
        如果(广告== NULL)
        {
            AD =新AdminData();
            ad.setId(INDEX_RA);
        }

        model.addAttribute(adminFormAjax,广告);
        返回adminFormAjax;
    }

    @RequestMapping(值=/ admin_ajax,方法= RequestMethod.POST)
    公共@ResponseBody AdminData adminSubmit(@ModelAttribute(adminFormAjax)AdminData广告,型号model)
    {
        rep.save(广告);
        model.addAttribute(adminFormAjax,广告);
        返回的广告;
    }

}
 

解决方案

所以答案崩溃。

  1. 在Thymeleaf不是多余的,它仍然会呈现HTML页面发送到客户端之前。阿贾克斯只是做了进一步的处理为您在客户端。
  2. 您可以使用提交按钮,以及,你只需要确保您的形式是结构合理的,你有JavaScript的监听你的提交按钮点击如

    $(#提交按钮)对('点击',函数(){//做的东西});

  3. 您处理所有异常/,你会与标准控制器的Ajax控制器内的问题。你需要单独处理的问题,在不同的层次。例如程序存储库级别的问题应在代表一级进行管理,控制/ POJO应该在控制器级别(或者是POJO,如果你使用一个用于处理)。你也应该通过捕捉一个全球性的媒体(如ControllerAdvice)任何异常。

  4. 的任何问题/错误,你拿起你应该通过在adminSubmit你回电话沟通回来,并管理AJAX相关客户端的响应。

As a followup to my earlier question about using Thymeleaf and preventing page refresh:

http://forum.thymeleaf.org/Preventing-page-refresh-Thymeleaf-amp-Spring-MVC-td4029155.html

Basically I had a working Spring MVC app that uses Thymeleaf to save form data. When the user saves the data the page would refresh (since I wanted to leave them on the page for more edits) and I wanted to eliminate the page refresh.

I have coded up some Javascript to use JQuery Ajax to post the data to my Spring MVC Controller. The trick seemed to be to not use a submit button, just a regular button and bind a JS function to it for sending the data to the server.

It all seems to work perfectly, but I want to make sure I understand what is happening. In particular I'm wondering if Thymeleaf is now redundant. I don't think it is because when I initially load the page Thymeleaf is still bound to the data bean. From using the debugger on the server side in the controller it looks like the post request calls the mapped method and passes in the data to the model.

I would appreciate your comments on whether or not this is the correct way to accomplish this.

Finally, how do I handle an error, say for example the repository fails to persist the data for any reason?

Thanks very much.

Here are the important parts of the form:

<FORM id="adminDataForm" action="#" th:action="@{/admin_ajax}" th:object="${adminFormAjax}" method="post">


<input type="button" value="Save Changes" id="post" onClick="sendData()" />

Here is the Javascript:

function sendData()
{
        $.ajax(
        {
            type: "POST",
            data: $("#adminDataForm").serialize(),
            cache: false,
            url: "/admin_ajax",
            success: function(data) 
            {
                alert("Your changes have been saved");
            },
            error: function()
            {
                alert("Error - Data not saved");
            }

        });
}

Here is the controller:

@SessionAttributes("adminFormAjax")
@Controller
public class TestController 
{
    final static protected long INDEX_RA = 2L;

    @Autowired
    private AdminDataRepository rep;

    @RequestMapping(value="/admin_ajax", method=RequestMethod.GET)
    public String adminFormAjax(Model model) 
    {
        AdminData ad = rep.findById(INDEX_RA);

        // If there is no configuration record, create one and assign the primary key
        if(ad == null)
        {
            ad = new AdminData();
            ad.setId(INDEX_RA);
        }

        model.addAttribute("adminFormAjax", ad);
        return "adminFormAjax";
    }

    @RequestMapping(value="/admin_ajax", method=RequestMethod.POST)
    public @ResponseBody AdminData adminSubmit(@ModelAttribute("adminFormAjax") AdminData ad, Model model) 
    {
        rep.save(ad);
        model.addAttribute("adminFormAjax", ad);
        return ad;
    }

}

解决方案

So breakdown of answer.

  1. Thymeleaf not redundant, it will still render the HTML page prior to sending to client. Ajax just does the further processing for you on client side.
  2. You can use submit button as well, you just need to ensure your form is properly structured and you have javascript listening for your submit button click e.g.

    $("#submitbutton").on('click', function (){//do stuff});

  3. You handle any and all exceptions/issues within your Ajax controller as you would with standard controller. You need to separate issue handling at different levels. e.g. respository level issues should be managed at rep level, controller/pojo should be at controller level (or pojo if you using one for processing). You should also be capturing any exceptions through a global medium (e.g. ControllerAdvice).

  4. Any issues/errors you pick up you should be communicating back via your return call in adminSubmit, and managing the relevant client response in ajax.

这篇关于Thymeleaf刷新页面随访 - 现在,随着AJAX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆