This is a simple demonstration of how to dynamically update a web-page with text fetched from a web server.
Name:
Reply:
When you click on the "Send" button the browser calls the onclick event,
which calls the update()
function:
function update() {
var name = dwr.util.getValue("demoName");
$.post("../../../dwr/jsonp/Demo/sayHello/" + name, {},
function(data) {
dwr.util.setValue("demoReply", data.reply);
}, "jsonp");
}
}
dwr.util.getValue()
is a utility to get the value of any
element, in this case an input field, but it could be a div or a select
box.
The next line is using the jQuery post function to make an asynchronous call to the server utilizing DWR's JSON capabilities. The first parameter is the URL for DWR's JSON service. The URL can be broken down as follows:
The result of the $.post function is that DWR will call the Demo.sayHello()
Java method:
public String sayHello(String name) {
return "Hello, " + name;
}
When the callback function is reached we call dwr.util.setValue()
which is a utility that takes the data you pass in
the second parameter and works out how to fit it to go into the HTML element
specified by id in the first parameter. This function is one of several neat
Javascript utilities that make working with DWR much easier.
<p>
Name:
<input type="text" id="demoName"/>
<input value="Send" type="button" onclick="update()"/>
<br/>
Reply: <span id="demoReply"></span>
</p>
function update() {
var name = dwr.util.getValue("demoName");
$.post("../../../dwr/jsonp/Demo/sayHello/" + name, { },
function(data) {
dwr.util.setValue("demoReply", data.reply);
}, "jsonp");
}
}
package org.getahead.dwrdemo.simpletext;
public class Demo {
public String sayHello(String name) {
return "Hello, " + name;
}
}
Note: In order to enable JSON/JSONP you must add the following init-param to your DWR servlet definition in your web.xml (This is a snippet and is not a complete web.xml).
...
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<display-name>DWR Servlet</display-name>
<description>Direct Web Remoter Servlet</description>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<param-name>jsonpEnabled</param-name>
<param-value>true</param-value>
</init-param>
...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC
"-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"
"http://getahead.org/dwr/dwr20.dtd">
<dwr>
<allow>
<create creator="new" javascript="Demo">
<param name="class" value="org.getahead.dwrdemo.simpletext.Demo"/>
</create>
</allow>
</dwr>