Grails, JQuery, and AJAX
Grails out of the box uses Prototype for its JavaScript framework, which means that developers have a number of GSP taglibs available which will automatically generate Prototype code to make AJAX-y calls.
Unfortunately, I “grew up” using JQuery, and thus feel more comfortable using JQuery as my JS framework. Luckily, Grails “has a plugin for that.” This means that if you’ve been using the Grails taglibs to generate your remote calls, you can install the plugin and it will generate JQuery code instead. Great for when you switch out your JS frameworks midstream…am I right?
Anyway, back on topic. First, let’s install the JQuery plugin. The official documentation is here, but, as you’ll soon see, they are a little incomplete. There are a number of ways to get your plugin installed.
1. From the command prompt, you can type in grails install-plugin jquery
2. From STS, you can press ctrl+shift+alt+g to open up the integrated Grails command line and type install-plugin jquery
3. From STS, you can select your project and press alt+g+m and install the jquery plugin from the UI manager
There is some bug preventing the plugin installation process from copying over the requisite jquery-1.4.4.js and jquery-1.4.4.min.js files over to your /web-app/js directory so you’ll then need to run the following:
grails InstallJQuery
You should see something like:
인용 하 다.
Downloading JQuery 1.4.4 ...
[mkdir] Created dir: D:\Development\redShoe\live\web-app\js\jquery
[get] Getting: http://code.jquery.com/jquery-1.4.4.js
[get] To: D:\Development\redShoe\live\web-app\js\jquery\jquery-1.4.4.js
.................
[get] Getting: http://code.jquery.com/jquery-1.4.4.min.js
[get] To: D:\Development\redShoe\live\web-app\js\jquery\jquery-1.4.4.min.js
........
JQuery 1.4.4 installed successfully
Once that’s done, add the following to your Config.groovy:
grails.views.javascript.library="jquery"
Then, in the layouts (or individual pages) that you’re going to use JQuery:
<g:javascript library="jquery" plugin="jquery"/>
Now comes the fun stuff. When doing AJAX calls, you can either use the Grails tag of remoteFunction or just do everything using JQuery’s $.ajax. I find that if you want to do simple stuff like refreshing a div with callback data, remoteFunction works just fine. When you start wanting to do more complex stuff, I actually find working with JQuery directly easier (but less portable). Your arch will have to make that executive decision.
Anyway, let’s do a simple example. You have a select box with id “topic” that when you select an option, you want to go find a list of books related to that topic. Your remote function might look something like:
${remoteFunction(
controller: 'book',
action:'ajaxFindBooksByTopic',
update:[success:'bookList', failure: 'errors'],
params:'\'topicId=\'+$(\'#topic\').val()',
onComplete:'somefunction();'
)}
To break it down, the remoteFunction has several components:
1. The controller determines which controller you’ll be hitting (in a MVC world)
2. The action defines which action on the controller you’ll be calling
3. The update field determines what div will be updated, either on success or failure
4. The params define the data you pass back. You’ll note that you have to do escaping of single quotes and a lot of random crap. This is one of the reasons why for more complicated stuff, I favor straight up JQuery.
5. The onComplete calls a JS function after everything is finished (whether it errored out or not)
In the example above, I made the remoteFunction actually query for the selected value on the “topic” selector. I can actually embed the remoteFunction directly on the selector’s onchange. If I do, the params would change to:
params:'\'topicId=\'+this.value'
On the controller side you would have a function such as:
def ajaxFindBooksByTopic = {
render Book.findAllByTopic(Topic.get(params.topicId))*.name
}
This example is simple, so I haven’t done any validation of the params passed in, but I think you get the idea. Also, if you’ve never experience the magic of Groovy, I’m sure that line just blew your mind. Essentially, through GORM (think groovified Hibernate), I find all Book objects by the Topic field, which I find via the topicId. Then, I loop through the list that’s returned back to me and return a list of names, which I then render. The rendered list is then updated in the “bookList” div. Mind. Blown.
But what happens when you want to do more complex things, like get a list of JSON objects back which you can then manipulate using JQuery?
$.ajax({
url:"${request.contextPath}/book/ajaxFindBooksByTopic",
dataType: 'json',
data: {
topicId: $('#topic').val(),
},
success: function(data) {
data.each(function() {
doSomething();
}
},
error: function(request, status, error) {
},
complete: function() {
doSomethingElse();
}
});
Fairly straightforward JQuery. What about our controller?
def ajaxFindBooksByTopic = {
render Book.findAllByTopic(Topic.get(params.topicId)) as JSON
}
Mind. Blown. Again. Grails can just convert your list of objects into a list of JSON objects and pass it back to your view. Then, you can iterate through your data and do as you please on the front end.
Hopefully, after my long-winded babbling, you can see how powerful Grails and JQuery can be together in building rich internet applications.
Referrence Link:
http://alexduan.com/2011/02/17/grails-jquery-and-ajax/
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
jQuery 전후 예이 기사에서는 jquery after() 및 before() 메소드의 예를 볼 것입니다. before() 메서드는 선택한 요소 앞에 지정된 콘텐츠를 삽입합니다. after() 메서드는 선택한 요소 뒤에 지정된 콘텐츠...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.