-
FEATURED COMPONENTS
First time here? Check out the FAQ!
'How to pass javascript object value into zk' or 'how to access zk component into javascript'
@creata87,
Calling JavaScript methods from Java is quite simple - you just use Clients.evalJavaScript(). Here is an example:
<zk> <script> function sayHello(){ alert("Hi there"); } </script> <zscript> import org.zkoss.zk.ui.util.GenericForwardComposer; public class MyComposer extends GenericForwardComposer { public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); } public void onClickButton(Event event) { String jsCommand = "sayHello()"; Clients.evalJavaScript(jsCommand); } } </zscript> <window apply="MyComposer"> <button label="Say Hello in JavaScript" forward="onClick=onClickButton()"/> </window> </zk>
In the future though, you might consider making a new thread to avoid confusion.
Regards,
Todd
..thank you for the quick reply :) yes, this is the easy way. unfortunately, it does not work for me as i have 3 files: .zul, .js and the .java controller. my guess is somehow the .js file has to be loaded in the controller..?
hello.zul
<zk> <?variable-resolver class="org.zkoss.zkplus.spring.DelegatingVariableResolver"?> <script src="/scripts/hello.js" /> <div width="100%" height="100%" apply="${helloController}"> <button id="helloButton" label="Hello"/> </div> </zk>
hello.js
function sayHello(){ alert("Hello world"); }
hello.java
import org.zkoss.zk.ui.util.GenericForwardComposer; public class HelloController extends GenericForwardController { public void onClick$helloButton(Event event) { String jsCommand = "sayHello()"; Clients.evalJavaScript(jsCommand); } public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); } }
You can certainly have external JavaScript files and I do this all the time with various jQuery libraries. I have never had a need to have the JavaScript loaded in a controller. The way you have code set up above should work just fine.
If you want to see another example, click here.
Regards,
Todd
Hi creata87 ,
it works for me.
Please reference to this sample and check all the path is correct.
function sayHello(){
alert("Hello world");
}
package j15d409$v1;import org.zkoss.zk.ui.*;
import org.zkoss.zk.ui.event.*;
import org.zkoss.zk.ui.util.*;
import org.zkoss.zk.ui.ext.*;
import org.zkoss.zul.*;public class HelloController extends GenericForwardComposer{
public void onClick$helloButton(Event event) {
String jsCommand = "sayHello()";
Clients.evalJavaScript(jsCommand);
}}
<zk>
<script src="Hello.js" /><div width="100%" height="100%" apply="j15d409$v1.HelloController">
<button id="helloButton" label="Hello"/>
</div></zk>
Asked: 2011-07-29 00:16:25 +0800
Seen: 434 times
Last updated: Aug 03 '11