Chapter 6 - Dojo Toolkit

advertisement
Chapter 6
DOJO TOOLKITS
Objectives
• Discuss XML DOM
• Discuss JSON
• Discuss Ajax Response in XML, HTML,
JSON, and Other Data Type
OVERVIEW
• There are many libraries/frameworks that help Ajax Web
development and abstract browser differences. The well
known programs include JavaScript based Dojo Toolkit,
Prototype framework, and Dynamic Web Remoting (DWR)
framework, Yahoo UI Library(YUI), and Java based Google
Web Toolkit (GWT).
• Dojo is a popular Open Source, portable DHTML
JavaScript toolkit that makes it easier for an Ajax developer
to build Ajax requests. Why is Dojo called a toolkit? Dojo
not only has a rich collection of libraries for JavaScript and
Ajax Web development, but also provides an extensive,
reusable, and customizable widget system supporting user
defined widgets, an enhanced event handling system, and
an io system which simplifies very complicated data
transfers between client and server.
• Dojo is a cross-browser oriented tool which
supports various Web browsers, such as IE,
Firefox, and Safari. It also solves Ajax browser
incompatibility problems in ordinary JavaScript.
• Dojo has a set of powerful JavaScript libraries
organized in packages. Dojo 0.4 used to have a
layered structure library hierarchy to organize all
Dojo functionality in packages. Dojo 0.9 and later
versions (currently 1.0) simplify the structure
where most Dojo functions (Dojo widgets, events,
io and others) are available in Dojo core base
packages; dijit and dojox (Extended Dojo project)
are sitting on top of Dojo core.
Dojo advantages
•
It wraps XMLHttpRequest and makes the
request construction and configuration much
easier.
•
It frees developers from detailed configuration
of Ajax XMLHttpRequest, and from parsing
and processing the responses back from the
server.
•
Its widget system is available in Dojo core and
Dijit namespace packages.
Ajax XML HttpRequest with Dojo
• A Hello world Dojo Ajax example:
The file “data.txt” has a text statement “Welcome to Dojo
Ajax!”.
This Web application just downloads the content of this
text file, places it in the HTML “div” tag “put_here”
placeholder, and displays it.
Assume the dojo core package dojo.js library is installed
in the dojo directory in the root directory under webapps
in a Web server such as Apache Tomcat.
If you browse this page, the “Welcome to Dojo Ajax” will
be displayed in the HTML page.
Here is the HTML file with a xhrGet Ajax request.
<html>
<head>
<title>Dojo Ajax</title>
<script type="text/javascript" src='dojo/dojo/dojo.js'></script>
<script>
function welcome() {
dojo.xhrGet( {
url: "data.txt",
// The load function is called on successful response from server
// It inserts the response to the HTML div “put_here” placeholder
load: function(response, ioArgs)
{ dojo.byId("put_here").innerHTML = response;
return response; },
Contd….
// The error function displays error message if server does not
// respond right
error: function(response, ioArgs)
{console.error("HTTP status code: ", ioArgs.xhr.status);
return response;}
});
}
//Invoke the welcome function when dojo starts up
dojo.addOnLoad(welcome);
</script>
</head>
<body>
<span>
<div id="put_here" ></div>
</span>
</body>
</html>
Three dojo methods are used:
The dojo.htrGet() is a request method provided in dojo core
package which facilitates XMLHttpRequest with GET request
method type. Dojo.htrPost is another request type method to
makes an XMLHttpRequest.
List of Dojo supported XMLHttpRequest functions, they all
take a property object(po) parameter.
• dojo.xhrGet(po)
• dojo.xhrPost(po)
• dojo.rawXhrPost(po)
• dojo.xhrPut(po)
• dojo.rawXhrPut(po)
• dojo.xhrDelete(po)
The XMLHttpRequest takes many argument properties. You can pass in a
Javascript object, which wraps all necessary properties to the xhrget
request as shown in the example.
The list of common request property arguments:
• url: String type, "/path/to/myServer.php". URL points to server
endpoint.
• content: Object type, {name: "value"}. These properties will be
serialized as name1=value2 and passed in the request.
• timeout: numeric type; it wait x milliseconds for the response. If this
time passes, then the error callback method is invoked.
• form: dojo.byId("formId"); it extracts form content and sends it to
server.
• handleAs: String type; "text" is default, it can be "json", "javascript",
"xml", etc.
• sync: Boolean type, default is false. It indicates
whether the request should be synchronous
(blocking) or asynchronous.
• headers: Object type specified in {} format. It is used
to send additional HTTP headers in the request.
• load: function(response, ioArgs){}. The load function
will be called on a successful response.
• error: function(response, ioArgs){}. The error
function will be called in an error case.
• handle: function(response, ioArgs){}. The handle
function will be called in either the successful or
error case.
Example
• One uses Dojo xhrGet function to get data from the server
and partially update the DHTML page without refreshing the
whole page, just like all Ajax requests do. The other uses
Dojo xhrPost method to post the DHTML form data to the
server and receives responses back from the server to
partiall update the client page.
• The next example shows a Dojo xhrPost Ajax request in the
following HTML file.
• The request is sent to a JSP called response.jsp, which will
respond to the Ajax xhrPost form request with a provided
user name, and say “Hello <user name>”.
<html>
<head>
<title>Hello User</title>
<script language="javascript" src="/dojo/dojo/dojo.js"></script>
<script language="javascript">
function onclick() {
var cl= {
// The page that parses the POST request
url: "response.jsp",
// Name of the Form you want to submit
form: 'myForm',
// Loads this function if everything went ok
load: function (message) {
mdiv = dojo.byId("Message");
mdiv.innerHTML = "<div
style=\"color:green\">"+message+"</ div>";
},
// Call this function if an error happened
error: function (error) {
console.error ('Error: ', error);
}
};
dojo.xhrPost(cl);
}
</script>
</head>
<body>
<span>
<form method='post' id='myForm'>
<h3> Example of using xhrpost</h3><br>
Enter Name: <input type='text' length="20" name='myName'
onkeyup='onclick();'/>
</form>
<div id='Message'></div>
</span>
</body>
</html>
Response.jsp
<%
String name =
request.getParameter("myName");
if (name != null && !name.trim().equals("")) {
out.print("Hello " + name + "!");
} else {
out.print("You didn't enter a name!");
}
%>
Dojo xhrGet request with
JSON data
• JSON data can be easily handled in the Dojo
xhrGet() Ajax request.
• Dojo greatly frees web developers from doing
complicated Ajax request configuration and
coding, such as parsing and converting the
JSON data into a JavaScript object.
• You just need to specify that the response is
handled in JSON format.
Assume the ajaxData.txt file on the server has JSON syntax data as
{
"Name": "Bill Jones",
"Education": {
"Undergraduate": "Physics",
"Graduate": "CS"
},
"Skills": [“Ajax”, “Ruby”]
}
• The following Ajax request retrieves a JSON object and puts
parsed information into the <div> with an id of 'json-data'.
• The XHRGET function takes JSON format argument, which
includes server url, data format handleAs, and a load function
(called back when response comes back successfully).
<html>
<head>
<title>Dojo xhrGet</title>
<!—Dojo Initialize -->
<script src='/dojo/dojo/dojo.js'
type='text/javascript'>
<script language="javascript">
function getJson () {
dojo.xhrGet ({
url: "http://server/ajaxData.txt",
handleAs: 'json',
// 'handleAs': ‘JSON’ tells Dojo to parse the data being
// retrieved from the URL by eval() function and convert it to a
//JavaScript JSON object.
load: function (responseObject) {
dojo.byId('json-data').innerHTML =
responseobject.skills[0];
},
error: function (error) {
console.error('Error: ', error);
}
});
}
</script>
</head>
<body>
<div id='json data'></div>
<a href='#'onClick='getJson();'> Display JSON data</a>
</body>
</html>
Summary
• The Dojo toolkit is a very useful and widely used
development tool for Ajax and other Web
development. It greatly simplifies the JavaScript
coding by way of the Dojo supported package
library.
• Specifically, it is much easier to construct an
Ajax XMLHttpRequest with Dojo than to use
JavaScript.
• Dojo supports a powerful widget system that lets
developers design their own widgets without
worrying about browser incompatibility
problems.
• The JSON standard for transferring data
between Web clients and servers is widely
accepted by almost all software
programming language and script
languages.
• It reduces the parsing complexity of XML
formatted data. People who are not
familiar with XML DOM API can still easily
construct and parse JSON data.
Download