ajax - Grails Ajax表-如何实现?

标签 ajax grails

我输入了:

<g:form role="search" class="navbar-form-custom" method="post"
        controller="simple" action="addEntry">
   <div class="form-group">
      <input type="text" placeholder="Put your data HERE"
             class="form-control" name="InputData" id="top-search">
   </div>
</g:form>

和表:
<table class="table table-striped table-bordered table-hover " id="editable">
    <thead>
        <tr>
            <th>Name</th>
            <th>Created</th>
        </tr>
    </thead>
    <tbody>
        <g:render template="/shared/entry" var="entry"
                  collection="${entries}" />
    </tbody>

</table>

Controller :
@Secured(['ROLE_USER', 'ROLE_ADMIN'])
class SimpleController {

def springSecurityService
def user

def index() {

    user =  springSecurityService.principal.username
    def entries = Entry.findAllByCreatedBy(user)
    [entries: entries]
}


def addEntry(){

        def entries = Entry.findAllByCreatedBy(user)
        render(entries: entries)
    }
}

我只想使用输入字符串中的数据动态更新表。
什么是最好的方法?
将不胜感激示例/解决方案

最佳答案

您可以使用带有Grail的formRemote标签的AJAX更新表。

输入形式

<g:formRemote 
    name="entryForm" 
    url="[controller: 'entry', action: 'add']"
    update="entry">

    <input type="text" name="name" placeholder="Your name" />
    <input type="submit" value="Add" />
</g:formRemote>

HTML表格
<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Created</th>
        </tr>
    </thead>
    <tbody id="entry">
        <g:render
            template="/entry/entry" 
            var="entry"
            collection="${entries}" />
    </tbody>
</table>

输入模板
<tr>
    <td>${entry.name}</td>
    <td>${entry.dateCreated}</td>
</tr>

控制者
import org.springframework.transaction.annotation.Transactional

class EntryController {

    def index() {
        [entries: Entry.list(readOnly: true)]
    }

    @Transactional
    def add(String name) {
        def entry = new Entry(name: name).save()

        render(template: '/entry/entry', collection: Entry.list(), var: 'entry')
    }
}

这个怎么运作

当按下添加按钮时,将调用添加 Controller 方法。 Controller 方法创建域实例并呈现_entry.gsp模板。但是,无需刷新浏览器页面,而是将模板呈现为AJAX响应。在客户端,将渲染的模板插入到带有id条目的tbody元素内部的DOM中,该ID条目由update属性在formRemote标记中定义。

请注意,使用这种方法,所有条目都将重新呈现,而不仅仅是新条目。只渲染新的比较麻烦。

资源资源
  • Complete source code for my answer
  • Grails AJAX
  • 关于ajax - Grails Ajax表-如何实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30240553/

    相关文章:

    hibernate - 用 Grails 动态查找器匹配 hasMany children

    grails - 在子文件夹中的 Controller 中使用Grails Form标签

    javascript - Proxy.php 无法使用 AJAX Solr 工作

    java - Spring MVC @RequestBody 不适用于 jquery ajax?

    javascript - j_security_check 使用 ajax

    grails - grails框架执行时的起点是哪个?

    javascript - AJAX 请求在 HTTP_STREAM_PARSER_READ_HEADERS 之后被取消

    jquery - 如何将用户 ID 传递到 django ajax post 中?

    grails - Grails-用户名的Spring Security UI电子邮件

    Grails Spring Security 默认配置 : How to define default user and password