Closed. This question needs to be more focused。它当前不接受答案。












想改善这个问题吗?更新问题,使其仅关注editing this post的一个问题。

6年前关闭。



Improve this question




所有,

我有两个问题,一个大一小。我的次要问题是,为什么这个简单的grails应用程序不起作用?

人员域
package ajax

class Person {
    String firstname
    String lastname
    int age


    static constraints = {
    }
}

HomeController
package ajax
class HomeController {

    def index() {
    render (view: "index")
    }
    def greet()
    {
        render "hi"
    }
    def getPersons()
    {
        def persons = Person.getAll()
        render(model: [persons:persons])
    }
}

index.gsp
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title></title>
    <g:javascript plugin="jquery" />
</head>

<body>
<div id="greeting"></div><br>
<button onclick='<g:remoteFunction action="greet" update="greeting"/>'>Click on me!</button>
</body>
</html>

最后我的主要问题是在index.gsp中,如果我想将按钮操作更改为getPersons,那么我如何通过ajax或jquery获取数据?如果我确实得到了数据,我将如何格式化g:remoteFunction中的数据,以便得到#greetingfirstname

最佳答案

以下解决方案应该起作用:

PersonController

package ajax
class PersonController {
  def index() {
    render Person.list(params) as JSON
  }
}

这是您的JSON后端。在前端,您可以使用普通的旧jquery进行ajax调用:
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<title></title>
<g:javascript plugin="jquery" />
</head>

<body>
<div id="persons"></div><br>
<button id='fetch-persons'>Fetch Persons</button>
<g:javascript>
$(document).ready(function(){
    $('#fetch-persons').click(function(){
        $.getJSON('/person/index.json', function(data) {
            $('#persons').html(JSON.stringify(data));
        });
    });
});
</g:javascript>
</body>
</html>

关于jquery - 如何通过ajax接收模型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25225815/

10-12 12:39
查看更多