简体   繁体   中英

Grails 2.0: Use Service in javascript function in GSP

I am just wondering how I can call a method of a service from within a function within a GSP. I tried the following but it does not seem to work:

<%@ page import="com.company.MyService" %>
<%
    def myService =grailsApplication.classLoader.loadClass('com.company.MyService').newInstance()
%>
<html>
<head>
[...]
<script language="javascript">
    function myFunction() {

        if (${myservice.isSomethingAvailable()}) {
           [...]
        }
    }
</script>

I am pretty new to javascript and Grails. Not sure how to achieve that or if it's even possible. Any help appreciated.

Thanks a lot

Jonas

  1. loadClass().newInstance() creates new instance of object, not spring bean (i mean it's not tied to grails infrastructure), i'm sure it's not what you want
  2. You can pass service from your controller, like render(model: [myService: myService]) (you have to declare it at controller lever)
  3. It's much more correct way is to pass result of this call, not service itself. I mean: render(model: [isSomethingAvailable: myService.isSomethingAvailable]) and test it as if ($(isSomethingAvailable)) {
  4. Notice that gsp is processed in server-side, not client-size. So it doesn't matter where you use your variable - on javascript code, or html code. And also, you can use gsp if tag: <g:if test="${isSomethingAvailable}"> instead of preparing javascript to check value on client-side (because you already know the result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM