Documentos de Académico
Documentos de Profesional
Documentos de Cultura
1-1
Objectives
1-2
What is AJAX?
The browser makes a HTTP request that may or may not be due to
a user action. For example, a clock application may automatically
make a HTTP request every second.
The reply from such a request does not contain a full new page. It
contains information that is used to update portions of the existing
page. For example, the clock application receives the current time
at the server as a part of the HTTP reply and updates the time
displayed in the page. The rest of the page remains as it is.
1-3
A Simple Example
Traditional Application
1. User selects an address.
2. A JavaScript function handles the onClick event of the list box.
3. The function submits the form. This causes the browser to send a HTTP request.
4. A Java Servlet or ASP page in the server side handles the HTTP request. It retrieves the
details of the selected address and returns a new HTML page. The page shows the
address details in the right hand side grey area.
Essentially, when the user selects an address, the entire page is replaced with a new page.
How AJAX Does it?
1. User selects an address.
2. A JavaScript function handles the onClick event of the list box.
3. The function uses certain JavaScript API to send a HTTP request. Note: the function does
not submit the form. The HTTP request is sent by invoking certain APIs that we will learn
shortly.
4. A Java Servlet or ASP page handles the request. It fetches the details about the selected
address. It returns a fragment of a HTML page that contains just the address details and
not anything else in the page (such as the list box).
5. Back in the browser side, a JavaScript function is called when the HTTP reply data is
ready. This function simply updates the content of the grey area to the right of the list box.
1-4
Browser
Server
onClick
HTTP Request
HTTP Reply
(New page)
Here we see the timeline of how the address book will behave according to the
conventional way of programming.
When the user selects an address in the listbox, the browser invokes the
onClick event handler function. This function causes a HTTP request to be
sent by submitting the form (by calling the form.submit() function). The server
would reply by sending a full new page. The browser will render the new page
in place of the old.
1-5
Browser
AJAX
Engine
Server
onClick
Send Request
Client side
HTTP Request
Update portions
of the page
Reply Data
Available
HTTP Reply
(HTML fragments)
Here we see the timeline of how the address book will behave according to the
AJAX way of programming.
When the user selects an address in the listbox, the browser invokes the
onClick event handler function. This function uses AJAX API to cause a HTTP
request to be sent. When the reply data comes back, the AJAX API invokes
another JavaScript event handler function. This function uses the data
available from the reply to update portions of the existing page.
What is Asynchronous about AJAX?
The AJAX Engine can invoke a JavaScript event handler function when the
reply data becomes completely available (or if an error occurs). This invocation
happens asynchronously at some time after the request was sent.
1-6
These two aspects of AJAX also form the two key goals of this course. We will
learn how to do these two tasks in increasingly sophisticated ways.
1-7
Indirect benefits:
The downside of a traditional application is that every HTTP request ends with
replacing the existing page with a new page. Essentially, the whole page is refetched and re-drawn. If the page is complex, this can lead to significant
delays in both obtaining the reply and rendering the page.
AJAX solves this problem. A HTTP requests results in small updates to the
existing page. This leads to a much better user experience. This also mimics
the desktop applications.
1-8
AJAX Technologies
Proper XML compliance means, we can use a XML parser API such
as JavaScript Document Object Model (DOM) to manipulate the
contents of the page. This is how AJAX applications update parts of
a page.
AJAX, XHTML and CSS2 are a powerful combination. To create feature rich
web applications that can match the functionality of a desktop application, you
will need to use all three technologies.
It is important to note here that AJAX does not depend on any specific server
technologies. We can build AJAX applications that can work with any type of
server code Java, ASP, PHP etc.
1-9
1-10
1-11
Methods
Properties
The property names are case sensitive. In Mozilla based browsers, the case
must be correct. Note, how "onreadystatechange" is in all lower case, where
as the other properties use mixed case (camel case).
1-12
Complete Example
<script type="text/javascript">
var req;
function startTest() {
req = createRequestSimple();
req.onreadystatechange = showReply;
req.open("GET", "response.txt", true);
req.send(null);
}
function showReply() {
if (req.readyState == 4 && req.status == 200) {
var div = document.getElementById("result");
div.innerHTML = req.responseText;
}
}
</script>
<button onclick="startTest();">Try It!</button>
<div id="result"></div>
When the Try It! button is pressed, the startTest() method is invoked. This
method creates a new XMLHttpRequest object by calling the
createRequestSimple() function. We have already seen how that function is
developed. Next, we set the onReadyStateChange property of the request
object to the showReply function. Then, we make a GET request for the
response.txt file. The value of the asynchronous flag is set to true. Next, we
send out the request with an empty body (GET requests do not have any body
text).
After the request is sent, the system automatically calls the showReply
function at various stages. In this example, we are only interested in the
successful completion of the reply. We check for the readyState to be 4 and
the status property to be 200. In that case, we, first, lookup the <div> object
with id "result". Then we set the contents of that <div> with the reply from the
server.
In this case, the content of response.txt is "Hello! This is a response from the
server".
1-13
The Timeline
JavaScript
event handler
Browser
XMLHttpRequest
Server
startTest()
open()
Client side
send()
HTTP Request
HTTP Reply
(HTML fragments)
Update portions
of the page
showReply()
Here, we see the same AJAX request processing diagram from a previous
page. This time, the actual JavaScript method names are shown in bold face.
This diagram should make it very clear as to how the example works.
Just as a summary, the startTest() JavaScript function is registered as the
onclick event handler of the button. When the button is clicked, the sequence
of activities shown above take place.
1-14
Review Questions
1.
2.
3.
4.
5.
6.
1-15
Review Answers
1.
2.
3.
1-16
Review Answers
4.
5.
6.
1-17
2-1
What is XHTML?
Since it is XML syntax, tools can easily parse and work with a
XHTML document.
Tools can easily validate the structure of a XHTML document.
The structure of the document can be easily manipulated by the
JavaScript DOM API to create powerful and rich client side
applications.
This is the primary reason for us to use XHTML with AJAX applications.
In this chapter, we will cover the basic syntax and the main differences with
HTML 4. That should be sufficient for you to apply your existing knowledge of
HTML 4 to write XHTML documents.
2-2
However, IE does not support this. So, keep using the MIME
type "text/html" until IE supports the actual MIME type.
2-3
2-4
2-5
Because, XHTML is pure XML, we can embed parts of it inside another XML
document (if that document's schema allows for it). In this example, we add a
<p> element inside the <c:description> element.
2-6
As you can see above, many syntaxes that are valid for HTML 4 are no longer
valid for XHTML.
2-7
In HTML 4, some elements (such as form and img) used the attribute
"name" and "id" interchangeably to identify the element.
The enumerated attributes must use a value from a specified list of possible
values. These values were case insensitive in HTML4. They must be in lower
case for XHTML.
2-8
That means characters like <, > and & will be treated specially.
Either use <, > and & or escape the whole body using
<![CDATA[.
The latter is recommended as using > etc in JavaScript could be
painful. See example below.
Note: Only FireFox enforces this behavior if application/xhtml+xml
MIME type is used. Since, we will not use that type, the use of
<![CDATA[ is strictly speaking not necessary but recommended.
<script type="text/javascript">
<![CDATA[
function startTest() {
var i = 10;
var j = 20;
if (i < j) {
alert("Special characters working");
}
}
]]>
</script>
2-9
2-10
<div id="d1">
<form id="f1" method="post" action="handle.jsp">
</form>
</div>
2-11
2-12
Review Questions
1.
2.
3.
4.
5.
2-13
Review Answers
1.
2.
XML
Advantages:
3.
2-14
Review Answers
4.
2-15
Review Answers
5.
2-16
3-1
What is DOM?
DOM stands for Document Object Model. According to this model, an XML
document is loaded into memory as a tree like hierarchy of elements.
DOM has dual purpose in a web browser:
Using the JavaScript DOM API, we can read data from and manipulate an XML
document. For example:
First, the XHTML or plain HTML document for a page is loaded as a DOM tree.
Second, you can construct an arbitrary XML document using the DOM API. We will
discuss this in a separate chapter.
Look up an element.
Create or remove elements.
Change the attributes of an element.
Simply put, this API allows us to alter the contents of a page that is currently
open in the browser.
Before DOM, one could only use document.write() to change the contents. As we will
see shortly, the DOM API allows for much more powerful page alteration.
The main purpose of the DOM API is to be able to alter a page after it has
been downloaded and rendered by the browser. We will cover that in details in
this chapter. The page doesn't have to be a valid XML (i.e., XHTML). It can be
a HTML document. The browser will internally convert the HTML to a valid
XML DOM document.
You can also parse or create any XML document using the DOM API. In other
words, DOM is not limited to an XHTML page. This will be covered in a
separate chapter.
3-2
Element Hierarchy
<html>
<head><title>Hello</title></head>
<body>
<p>Hello world.</p>
<p class="w1" id="p1">How are you?</p>
</body>
The Document
</html>
<html>
<head>
<body>
<title>
<p>
Attribute:
class
<p>
Attribute:
id
The example above shows how the DOM API organizes the elements in a
XHTML document in a tree like structure. It is interesting to note that the
attributes of an element are also stored as children nodes.
At the very root of the hierarchy, we have a document object that represents
the entire XHTML document. The immediate next level child is usually the
<html> element. In this example, the <html> element contains two children a
<head> and a <body>.
3-3
DOM Standardization
These browser specific deviations are clearly labeled in this chapter. Here,
Mozilla stands for FireFox and Netscape. And, IE stands for Internet
Explorer.
Mozilla: http://developer.mozilla.org/en/docs/Gecko_DOM_Reference
In this chapter, we deal with two types of browsers. Mozilla covers Netscape
and FireFox. We also cover Internet Explorer.
3-4
You can also load any other XML document using a URL or create a brand
new document from scratch.
The documentElement and firstChild properties both return the top level
element of the document. For a valid XHTML document this will be the
<html> element.
However, different browsers behave differently in this regard.
1. documentElement IE and FireFox return the <html> element.
2. firstChild FireFox returns the <html> element. IE returns any comment or
<!DOCTYPE> element that may appear before the <html> element.
As a result, to get a hold of the <html> element, use the documentElement
property.
Example:
function showDocProperties() {
alert("documentElement: " + document.documentElement.nodeName);
}
3-5
Important methods:
In the example below, we find the elements by id or name and change their background color.
function findById(id) {
var e = document.getElementById(id);
if (e != null) {
e.style.backgroundColor = "yellow";
} else {
alert("Could not find element by ID: " + id);
}
}
function findByName(name) {
var list = document.getElementsByName(name);
if (list == null || list.length == 0) {
alert("Could not find element by name: " + name);
return;
}
for (var i = 0; i < list.length; ++i) {
var e = list[i];
e.style.backgroundColor = "red";
}
}
<p id="p1">This is a paragraph</p> findById("p1");
<div name="div1">Text</div> findByName("div1");
3-6
Important methods:
Example:
In this example, we will write a function that adds a new line in this paragraph.
<p id="log_area"></p>
The following function creates new text node as well as new elements.
function logMessage(msg) {
var e = document.getElementById("log_area");
var txtNode = document.createTextNode(msg);
e.appendChild(txtNode);
var br = document.createElement("br");
e.appendChild(br);
}
//use the function from an XHTML document.
<p id="log_area">
<b>Log messages:</b><br/>
</p>
<button onclick="logMessage('TRACE: A sample message');">Log</button>
3-7
So, all Elements are also Nodes but not vice versa.
Comments
DOCTYPE declaration
Elements These are actual tags such as <p> and <form>.
Attributes of an element are also represented as a Node.
Element extends Node or inherits from Node in the Object Oriented
parlance.
Some complex elements, such as <form> and <table>, extend the Element
and add additional behavior. They will be discussed in a separate chapter.
The W3C DOM specification defines the behavior of the Node and Element
interface. JavaScript implements these interfaces. In this chapter, we will
discuss the behavior of the Element interface which extends Node. In a
separate chapter, we will discuss more advanced element types, such as a
table, that extends Element and adds more functionalities.
3-8
3-9
Important properties:
Returned in upper case by IE and FireFox if "text/html" MIME type is used. For
"application/xhtml+xml", lower case names are returned.
nodeType Integer value indicating the nature of the node. See list
below.
textContent (Mozilla), innerText (IE) The body text of an element. The
difference from innerHTML is that, tags for all child elements are stripped
out.
ownerDocument The document object that eventually owns this
element.
style Returns the style object. More on style object later.
className The name of the style class of the element.
parentNode Returns the node this element's parent.
3-10
Important methods:
appendChild(element) Adds a child element at the end of the list of children. If the element
being added is already in the DOM document, it will be first removed from its current parent.
Same goes for insertBefore.
insertBefore(element, beforeElement) Adds a new child element before the child element
beforeElement. Note: Element beforeElement must be a child of the current element for which
insertBefore is called. As a result, a common way to call insertBefore is:
getElementsByTagName(tag) Returns an array of children elements that match the tag name
(such as "p" or "img").
getAttribute(name) Returns the value of an attribute given its name. IE has unusual behavior
for some properties. For example, use getAttribute("className") to get the "class" attribute.
You can set extended attributes in HTML: <div foo="bar"/>. div.getAttribute("foo") will return "bar".
setAttribute(name, value) Sets the value of an attribute. You can set extended attributes not in
XHTML spec: div.setAttribute("foo", "bar").
setAttributeNode(attribute) Sets an attribute node object. Attribute nodes are created using the
createAttribute method of document.
getAttributeNode(name) returns the attribute node object given its name.
3-11
Important methods:
3-12
Using attribute:
<button id="b1" onclick="doSomething();">Click me</button>
2. By setting property:
var btn = document.getElementById("b1");
btn.onclick = doSomething;
<button id="b1">Click Me</button>
3. Directly defining a function.
<script type="text/javascript">
function init() {
var btn = document.getElementById("b1");
btn.onclick = function() {
alert("Event handler called");
};
}
window.onload = init;
</script>
<button id="b1">Click Me</button>
Option 2 or 3 leads to cleaner HTML as the HTML body no longer has to specify JavaScript event handlers.
3-13
3-14
Key methods:
Common Features
left, top The left and top coordinate of the window, in pixels, relative to the
desktop.
width, height Width and height of the content area of the window in pixels.
This does not include scrollbars, status bars, menu bars etc.
menubar If true, the menubar is shown.
toolbar If true, the toolbar is shown.
location If true, the address bar (showing the URL of the page) is shown.
status If true, the statusbar is shown.
3-15
Events
3-16
3-17
Methods:
3-18
Review Questions
1.
2.
3.
4.
5.
3-19
Review Answers
1.
2.
3.
4.
5.
3-20
4-1
The request object forms the core and perhaps the only API
required to perform AJAX style asynchronous communication
with the server.
Currently, there are two separate but highly compatible
implementations of the request object.
http://www.w3.org/TR/XMLHttpRequest/
4-2
MSXML2.XMLHttp.5.0
MSXML2.XMLHttp.4.0
MSXML2.XMLHttp.3.0
MSXML2.XMLHttp
Microsoft.XMLHttp
4-3
4-4
Properties:
Example:
req.onreadystatechange = func;
//The event handler does not receive any parameter
function func() {
}
4-5
Properties:
responseText Contains the reply body data. System converts the text into
16bit UNICODE from the source encoding.
Source encoding is set in the Content-Type HTTP reply header. If missing, UTF-8
is assumed.
Note: responseText does not include the reply headers.
Reply body is available in readyState 3 or 4 only. Otherwise, this property will
return empty string. If readyState is 3, this property will return the partial reply
data that is currently available. When the state changes to 4, all the reply data is
available.
The HTTP reply MIME type must be "text/xml" or "application/xml" for the
request object to automatically parse the body and create the DOM document.
The DOM API, already discussed in the context of a XHTML document, also apply
to this DOM document.
4-6
Methods:
4-7
Methods:
4-8
Methods:
4-9
Methods:
4-10
4-11
4-12
Example
In this example, we submit a login form using a POST request. There are two
text boxes with ID "user" and "password". We retrieve their values (text
entered by the user) and form the request body. We also make sure that the
encoding of the Content-Type header is set to UTF-8. System always encodes
the request body text using this encoding. The correct content type will pass
on the encoding information to the server that can then correctly process the
request.
function sendAjaxRequest() {
request = createRequest();
var user = document.getElementById("user").value;
var password = document.getElementById("password").value;
var body = "user=" + escape(user) + "&password=" + escape(password);
request.onreadystatechange = showResult;
var url = "LoginServlet";
request.open("POST", url, true);
request.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
request.send(body);
} Solutions Inc. 2010
(C) Web Age
4-13
This makes it difficult for the event handler method to get the
request object for which the method is being invoked.
For example, say, the user interacts with the application which
causes a request to be sent. While the user is waiting for that
result, she does something else, for which another request needs
to be sent. Now, the second request will cause the first one to be
aborted or cause other problems with race conditions.
4-14
A good solution to this problem is to build a simple framework that uses an inner function.
Example:
4-15
For example a user may request to remove several items from the
shopping cart without waiting for the reply for each request.
For example, for each item successfully removed from the cart, the
callback may show a status message showing the name of the
product that was removed.
4-16
Variables like xhr are created in the stack of the outer function.
ECMA script specification does not mention exactly when the stack of
the outer function will be destroyed to free up memory.
IE does not appear to destroy the stack at all. this leads to severe
memory leak.
To solve this problem, we explicitly set the variables of the outer
function to null when we are done using them. This solves the memory
leak problem.
We are done with the request object after the readyState changes to 4.
4-17
The ajaxPost function is similar to ajaxGet, but, has a few notable differences.
The method allows concurrent requests. Also, The POST body data is sent as
the requestData object. An example on how to call this function will show you
how the requestData object is constructed.
var requestData = new Object();
requestData.orderId = "1000";
requestData.operation = "CANCEL";
ajaxPost("ManageOrderServlet", requestData, showStatus, null);
The example above will send a POST request for the ManageOrderServlet
URL. The request body will look like this:
orderId=1000&operation=CANCEL
4-18
Mozilla XmlHttpRequest
Extensions
The three event handlers mentioned above have a key distinction from the
onreadystatechange event handler. A function registered with the latter, as we
have already discussed, does not receive any parameters. For these three
events, the function will receive an event object. This is consistent with the
DOM event model. For example:
function sendRequest() {
var req = new XMLHttpRequest();
var req.onload = processReply;
//req.open and req.send omitted for brevity
}
function processReply(evt) {
//Locate the request object
var req = evt.target;
var reply = req.responseText;
//Do something with the reply
}
4-19
Mozilla XmlHttpRequest
Extensions
Methods:
4-20
IE Microsoft.XMLHTTP
Extensions
Property:
4-21
Ajax Caching
This way, the application code does not have to know if the
reply data came from the cache or the network.
4-22
The server side code can use the Expires or the Cache-Control reply
header to control the duration of the cache in the browser.
To set a time limit for the cache of a GET request, do one of the
following:
Set the Expires header to the expiration date and time in this format: Wed,
13 Feb 2008 16:00:00 GMT. Or,
Set the maximum age of the cache in seconds by setting the Cache-Control
header's max-age property. For example, a value of max-age=30 will
cause the browser to use the cache for 30 seconds only.
4-23
The previous techniques either disable cache or set a fixed expiry for the cache.
Alternatively, the Last-Modified reply and If-Modified-Since request headers can be
used to perform more dynamic cache invalidation. See use case below.
When the data is first fetched using a GET request, the reply should contain two
headers:
In this scheme browser based caching is disabled and every GET request is sent to the server.
The server decides if data has changed since the last reply. A reply document is sent only if
data has changed. This saves unnecessary database access and reduces the size of the reply
document.
Cache-Control is set to max-age=1 to set a low cache age and effectively disable cache.
Last-Modified is set to the time when the reply data (such as product information) was last
modified in the database.
The reply from this first request for the URL is cached by the browser. Even though,
max-age is only 1 second, the cached data may be used as we will see next.
When a GET request is made for the same URL again, the browser behaves as follows:
The If-Modified-Since request header is set to the value of the Last-Modified header from the
cached reply. JavaScript application code doesn't have to do anything.
The server side code should inspect the value of the If-Modified-Since header. If the database
data has not changed since that time, it should reply with a 304 status code and an empty
body. This avoids expensive database access and reduces HTTP network traffic.
When the browser sees a 304 reply code, it fetches the reply data from the cache. The
responseText property of the XMLHttpRequest object is set to that data.
Let us say that you are sending a request for a URL that returns product information. This
information can be cached by the browser as long as the product data has not changed in the
server. This feature is difficult to implement using the Cache-Control reply header alone since
we have no idea when the product data will be modified.
Example headers for first reply to a GET request:
HTTP/1.1 200 OK
Last-Modified: Wed, 13 Feb 2008 13:49:17 GMT
Cache-Control: max-age=1
Content-Type: text/plain
Content-Length: 28
A subsequent GET request will look like this:
GET /AjaxWeb/GetProductData?id=1 HTTP/1.1
Host: nero:8080
If-Modified-Since: Wed, 13 Feb 2008 13:49:17 GMT
Server can return with a 304 status code and an empty body:
HTTP/1.1 304 Not Modified
Server: Apache-Coyote/1.1
4-24
Review Questions
1.
2.
3.
4.
5.
4-25
Review Questions
6.
7.
8.
9.
10.
4-26
Review Answers
1.
2.
3.
4.
5.
True
The onreadystatechange property is used to
specify the event handler (i.e., JavaScript function)
that is invoked at various times after the request is
sent.
readyState should be 4 and status should be
200.
responseText simply corresponds with the text
contained inside the reply body and can contain
markup. responseXML is a DOM document
representing the reply body.
open and send
4-27
Review Answers
6.
7.
8.
9.
10.
4-28
5-1
Objectives
5-2
Introduction
CSS1 was introduced by the W3C in 1996 as the Cascading Style Sheet Level
1 specification. The general idea was to reduce the dependency of HTML
documents on granular elements for visual formatting while adding capabilities
that HTML simply didn't possess (e.g. color).
5-3
3
New in CSS2
The W3C recognized with the growing popularity of the Web selectivity was a
challenge of major importance. The choice of selectors in CSS Level 2 is very
impressive.
The asterisk has the widest influence on the document tree. For example, this
specification sets the margin of all boxes to 3 centimeters:
* { margin: 3cm; }
5-4
New in CSS2
run-in
compact
Run-in and compact join the list of boxes from CSS1: block, inline and none.
Property value inheritance is not new, but now can be explicitly requested
using inherit. This is of course the default.
5-5
Simple Example
Note the <link> tag; this directs the browser to apply the external style sheet to
the document. Here is the entire style sheet:
/* Simple CSS */
h1 { font-family: Copperplate Gothic Light; color: blue}
.important { font-family: Bookman Old Style; font-size: 12pt;
font-size: 12pt; color: red; text-decoration: underline;}
This is a simple text file. We will study alternative ways of styling on later
slides.
5-6
Formatted Output
The <h1> rendering reflects the rule imposed by the style sheet. The second
paragraph is dramatically different from the first paragraph in presentation. To
attempt this rendering with HTML elements would be cumbersome, and would
require that several additional tags be hard-coded in the HTML source.
5-7
Unformatted Output
Now the styling is absent and the browser uses default rendering. Notice that
the text in the second paragraph is rendered identically to first paragraph. The
relative important of paragraph two is not as obvious as it was on the previous
slide.
5-8
8
Basic Syntax
5-9
9
Use an external style sheet from an HTML file using the <link> element.
<head>
<link rel="stylesheet" type="text/css" href="CSSSimpleExample.css" />
</head>
When coded in the HTML file, use the style element or the style attribute (or)
both.
You can import an external style sheet using the @import directive. Example:
@import "HoverStyles.css"
The @import must be coded before the first rule in the style sheet.
This directive must be included in the <style> tag scope if coded in the HTML
document.
Use of external style sheets is beneficial because an arbitrary number of HTML documents
may link to that file. An HTML document can link to an arbitrary number of style sheets.
Inline styles override any styles listed in the <head> section. Any styles listed in the <head>
section override any styles available in an external style sheet.
5-10
10
Value Types
cm - Centimeters
in - Inches
pt Points
mm - Millimeters
Now the height of a line in the paragraph will be 150% taller than 24 points.
URL value type; used to locate images and other resources. e.g.:
body { background: url("images/leaves.jpg"); }
Value types are coded after the property, following the colon (:). Length value
types permit you to specify, for example, the font size in a variety of ways.
Consider the following where we display the paragraph text in letters 2
centimeters high:
<p style="font-size: 2cm;">This is BIG text!</p>
We can also use the more traditional points:
<p style="font-size: 12pt;">This is more normally-sized text!</p>
5-11
Value Types
There are several predefined names that can be used for color; among them
aqua, black, blue, gray, green, olive, white, yellow (complete list follows on a
later slide). The RGB specification permits you to "compose" a color based on
relative amounts of red, green or blue. 0 (zero) indicates no contribution from
that color; 255 (ff in hexadecimal) indicates the maximum contribution.
5-12
12
Selectors
Selectors are the core of the rule. A selector acts as a filter. System applies the
selector to find out which XHTML elements will be eligible for a styling rule.
At a broad level, there are two types of selectors:
Element identifier These selectors use an element's tag name, attribute or position
among its siblings in the DOM tree to filter the elements. For example, when the name
of an HTML element is used as a selector, the browser applies the rule to all such
HTML elements.
A pseudo-class. This type selector uses the dynamic state of an element to identify it.
For example, to underline a paragraph when the mouse pointer "hovers" over it:
p:hover { text-decoration: underline ;}
To change the color of a visited hyperlink to green:
a:visited { color: green; }
After the system applies the selectors, an XHTML element may be eligible for
multiple styling rules. Rule preference is:
inline style
embedded style sheet
external style sheet
If class and ID attributes are present, then ID wins because IDs are more specific than
classes. In XHTML, an ID attribute value must be unique. Similarly an attribute selector
(denoted by [] )is preferred over class.
5-13
More on Selectors
p.warning {color: red} /* This class can be used with p tag only */
The type selector will apply the rule to all element types, or tags, in the
document that are of that type.
The class selector is particularly powerful because the web page author can
selectively determine what tags should receive the indicated styling. Notice
that a dot must precede the class name when defined in the style sheet. Tags
that do not reference the class using the class attribute will not receive the
styling.
14
5-14
More on Selectors
The ID selector matches any element type that has the associated id
attribute.
The following will apply only to <p> tags that have an id="abc":
p#abc { font-size: 24pt; }
The child is exactly one level lower on the document tree from the parent. Separate a
parent selector from child by ">".
For example, to apply a font-family to only <p> tags that are children of <div> tags:
div > p { font-family: Helvetica; }
#id1 > #id2 {...} //Select element with id id2, child of id1.
A descendent is any level lower than the parent. See details below. Separate parent
selector from a descendent by space.
For example, to apply a font-family to only <p> tags that are contained (descended
from) <div> tags:
div p { font-family: Helvetica; }
5-15
More on Selectors
The :hover pseudo class is very popular. Consider the following HTML:
<p>Underline this paragraph when the pointer is rolls over it!</p>
To apply the desired underlining, code this rule
p:hover { text-decoration: underline ;}
Note that we used a "p" in front of the pseudo-class name. This targets the
element type to which the rollover effect applies.
5-16
16
Grouping Elements
#d1 > #d2 > #d3 {color: red} Selects d3 that is a grandchild of d1
#d1 #d2 #d3 {color: blue} d3 is a descendent of d2 which descends from d1.
h3
div
17
5-17
5-18
18
Here are the rules used to generate the box that is displayed on the slide:
div {background: green;
margin: 20px 30px 20px 30px; /* top right bottom left */
padding: 20px 30px 20px 30px; /* top right bottom left */
border-style: groove; border-width: thick; border-color: blue;}
p { background: gray;
margin: 10px 15px 10px 15px; /* top right bottom left */
padding: 50px 60px 50px 60px; /* top right bottom left */
border-style: dotted; border-width: medium; border-color: blue;}
5-19
Box Properties
The preceding example gave an idea of the richness of the box model.
Margin area can be controlled by specifying length values for top, right, bottom
and left.
Padding area can also be controlled as above.
You can specify each dimension with shorthand or with individual properties.
Shorthand:
margin: 20px 30px 20px 30px; /* top right bottom left */
Individual properties:
margin-top: 20px;
30px;
Many border types are supported; the following is a sampler of values supported
by the the border-style property:
dotted
dashed
solid
double
groove
5-20
The <div> tag has inline content ("Div Text") and block content (the <p>
tag).
5-21
21
Types of Boxes
5-22
22
Types of Boxes
5-23
Display Property
The display property specifies what box type will be generated for an HTML
element.
You can request a different box type by including this property in your style sheet.
For example, a <span> tag has inline formatting by default-to change this behavior to
block:
block
run-in
inline
compact
p { display : inline; }
...
<p>This is not </p>
<p>the usual paragraph behavior!</p>
Displays:
5-24
Positioning Schemes
Normal flow
Floats
Absolute
By default, the browser will use normal flow and boxes will be laid out
according to block and inline guidelines. Properties such as "top" and "left" will
be ignored.
5-25
The positioning scheme is requested on the elements that will be affected. For
example, we may wish to relatively position spans within a paragraph:
span { position: relative; display: block; line-height: 12pt; font-size: 12pt; }
span.shiftedRight {top: 0pt; left: 120pt;}
span.shiftedUp {bottom: 12pt; left: 240pt;}
...
<p>Paragraph block
<span>Block box 1</span>
<span class="shiftedRight">Block box 2</span>
<span class="shiftedUp">Block box 3</span>
</p>
The positioning scheme if the containing block (in this case a <p> block) is not
relevant.
5-26
26
Relative Positioning
Relative positioning means that once a box has been laid out (in
its containing block), its position will be shifted relative to where
it would have been placed if relative had not been requested in
the first place.
The shifted amount can specified as:
Let's consider the example from the previous notes. If the class attributes
where removed, the output would look like:
Paragraph block
Block box 1
Block box 2
Block box 3
which of course is customary. But if the styling in the previous notes is
applied, the output is dramatically different:
Paragraph block
Block box 1
Block box 3
Block box 2
5-27
If the style attribute is omitted in the example on the slide, then the text will be
placed to the right of the image and on the last line.
Notice that a margin property is present; this is important so that the text is
separated from the image edge and hence is more readable.
5-28
28
5-29
Absolute Positioning
Earlier we saw this example (we have now added the absolute value for span
positioning and relative for paragraph positioning):
p { position: relative; }
span { position: absolute; display: block; line-height: 12pt; font-size: 12pt; }
span.shiftedLeft {top: 0pt; left: 120pt;}
span.shiftedUp {bottom: 12pt; left: 240pt;}
The <p> tag is the positioned ancestor. The HTML markup remains
unchanged. The output is:
Block box 3
Paragraph block
Block box 2
Block box 1
5-30
Layered Presentation
For example:
span.location { top: .5in; left: .5in;}
...
<span class="location" style="z-index: 1">Block box 1</span>
<span class="location">Block box 2</span>
If the z-index property were not coded, then the text "Black box 2" would
appear.
To enhance the example, we used:
span { position: absolute; border-style: groove; border-width: thin;
background-color: white; }
Otherwise each box is transparent and the rendering may not be desirable.
The background-color property is discussed later.
5-31
Color Property
Recall the earlier discussion on RGB when color value types were presented:
p { color: #0000ff; } /* blue */
p { color: rgb (0,0,255); } /* blue*/
5-32
Background Properties
background-color
background-image
background
5-33
Font Properties
As of HTML 4.0 strict, <font> was obsolete; font properties are
to be used instead. Common properties are presented here.
font-family Sans Serif, Helvetica, Bookman Old Style, etc.
5-34
Summary
5-35
6-1
Event Handling
You can create custom event types and fire them using the DOM
API.
6-2
Created
Initialized Various properties are set.
Dispatched The event is fired
Handled Event handlers are called.
so far, you may have written event handler functions without knowing anything
about the Event object. In the next couple of slides we will learn about it in
details so that we can make our event handlers more powerful.
6-3
3
Key properties:
type The name of the event. Such as "click" for the onclick event.
altKey, shiftKey, ctrlKey If Alt, Shift or Control key was pressed when the
event took place.
clientX, clientY The coordinate of the point where the event took place
relative rto the content area of the page.
screenX, screenY The same but relative to the top left corner of the
desktop.
timestamp Time when the event took place.
target (Mozilla), srcElement (IE) The original element that fired the event.
currentTarget (Mozilla only) The element where the event handler is
registered.
bubbles If true, if a child element fires an event, it will cause event
handlers associated with the parent elements to be also called. Mozilla only.
button the mouse button clicked. See details below.
keyCode (IE)/which (Mozilla) The UNICODE integer ID of the key pressed.
6-4
4
Key methods:
The prevetDefault() function works as follows. Let us say that a user clicked on
a hyper link. By default, the browser will first call all the onclick event handlers.
Then it will proceed to load the document pointed to by the hyperlink. If from
an event handler function, we call the preventDefault() function for the event
object, system will continue to execute the remaining event handlers (if any).
But, it will not load the document pointed to by the hyper link.
The preventDefault() function works only for events that are cancelable. An
event is flagged at cancelable when it is first initialized. We will discuss event
initialization later. In Mozilla, the event type supports a cancelable property
that indicates if an event can be canceled. Example:
//This will work in Mozila only
if (theEvent.cancelable) {
theEvent.preventDefault();
}
5
6-5
DOM Hierarchy
Event Bubbling
<table onclick="func2();">
Element
<tr onclick="func1();"> Element
<td> Element
In this example, a table element contains a row element (<tr>) which contains
a cell element (<td>).
The function func1() is registered as the onclick event handler for the row. The
function func2() is registered as the event handler for the whole table.
If a user clicks on the cell, system will go up the chain of hierarchy and call
each element's onclick event handler. In this case, the cell does not have an
event handler. So, nothing is done with the cell. System proceeds to call
func1() and then func2(). This behavior is called bubbling. Not all events
bubble up the chain. When you create your own event object, you can disable
bubble (even for events such as onclick that would otherwise bubble).
6-6
6
Creation and initialization of events is only required if you are writing code to
fire events. Normally, a browser will take care of these things. Only advanced
programs need to fire event artificially.
Parameters of Event Initialization Functions
name Indicates the type of event. These names are usually same as the
event handler properties with the "on" prefix removed. For example, "click",
"mousedown", "change" and "load".
bubbles If true, all event handlers for the element that fired the event as well
as it's ancestors in the DOM tree will be invoked. For example, if a <div>
element contains a <p> element and the <p> element fires an event, the
handler for the <div> element will also be invoked.
cancelable If an event is cancellable, then an event handler method can
cancel further firing of the remaining event handlers.
view Pass the window object here.
detail - the Event's mouse click count.
screenX, screenY, clientX, clientY Discussed in the event properties section.
ctrlKey, altKey, shiftKey, metaKey, button Discussed in event properties
section. The metaKey property applies to MAC machines only, where there is
a meta key.
relatedTarget When the mouse leaves an element and enters another one,
an onmouseout event is fired for the first element. The second element is set
as the related target.
(C) Web Age Solutions Inc. 2010
6-7
7
Dispatching an Event
element.dispatchEvent(event)
element.fireEvent(name, event)
name The type of event. Such as "onclick",
"onload".
Normally an event is fired after a user interacts with an element, such as click
on a button. DOM allows a program to fire an event programmatically without
any user interaction.
6-8
Example
function mimicEventMozilla() {
var b2 = document.getElementById("b2");
var evt = document.createEvent("MouseEvent");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
b2.dispatchEvent(evt);
}
function mimicEventIE() {
var b2 = document.getElementById("b2");
var evt = document.createEventObject();
evt.screenX = 10; evt.screenY = 20; //Initialize
b2.fireEvent("onclick", evt);
}
The example above shows how to create, initialize and fire events, depending
on the browser. In both cases, we fire the clicked event for a button with id
"b2". If that button has an onclick event handler, such as below, it will be
invoked.
<button id="b1" onclick="b1Clicked();">Button One</button> <br/>
<button id="b2" onclick="b2Clicked();">Button Two</button>
The b1Clicked() and b2Clicked() functions can be written like this:
function b1Clicked() {
try {
mimicEventIE();
} catch(e) {
mimicEventMozilla();
}
}
function b2Clicked() {
alert("Handled event in b2");
}
No matter which button you click, the b2Clicked() function will be eventually
called.
6-9
9
Handling Events
6-10
<button onclick="func2(event)">OK</button>
Here, event is a special keyword that instructs the browser to supply the
event object as the first parameter. Another example that uses the "this"
keyword as well.
The "this" keyword points to the DOM Element object for which the
event handler was registered. Due to bubbling, this may or may not be
the actual element where the event took place.
function func1() {
//This is the most common type
}
function func2(e) {
//Get event properties
var x = e.clientX;
var y = e.clientY;
}
function func3(e, data1, data2) {
//data1 should be "Hello"
//data2 should be "World"
}
6-11
11
The event handler properties are in all lowercase and match the
corresponding attributes in XHTML (such as onlick, onkeydown,
onload etc.).
The problem is, this way, the function can not receive the event
parameter.
var e = document.getElementById("b1");
e.onclick = func1;
FireFox (Mozilla) provides a work around, see below. IE does not have
any work around.
If you wish to set the event handler from JavaScript and wish to
access the event object from the handler method, register the event
using an API call.
No Event Supplied
function func1(event) {
//event will be null for Mozilla and IE
}
FireFox Work Around
Register an anonymous function that will receive the event object as
argument.
e.onclick = function(evt) {sendRequest(evt);};
function sendRequest(event) {
6-12
12
In IE, call the attachEvent method of the element firing the event.
attachEvent(name, handler)
name The type name of the event. Such as "click", "change" or "load".
handler The function handling the event. Receives the event object.
capture If true, the parents of this element will not get the event. usually
set to false.
name The type name of the event. Such as "onclick", "onchange" and
"onload".
handler The event handler function. Receives the event object.
This way, you can attach as many event handlers as you want. See
example below. The order of invocation of the event handlers can
be browser dependent.
6-13
13
6-14
Best Practice
Generally, do not use XHTML markup to register an event handler.
Use DOM API to externalize the handler registration way from the
XHTML markup.
function registerIEEvents() {
var b1 = document.getElementById("b1");
b1.attachEvent("onclick", func1);
b1.attachEvent("onclick", func2);
External JavaScript
}
File
window.onload = registerIEEvents;
As you can see above, the XHTML becomes very clean. You don't have worry
about the different function names and event handler properties. All that
details can be externalized in a separate JavaScript file. As an added benefit,
you can attach multiple event handlers for the same event.
You can either use the attachEvent or addEventListener method or set the
event handler properties. Using the latter, approach, the Javascript code will
look like this:
function registerIEEvents() {
var b1 = document.getElementById("b1");
b1.onclick = func1;
}
This approach is browser neutral, but we can only attach one handler.
6-15
15
6-16
We will learn about CSS2 in details later. Here, we will discuss how
to manipulate styles using the DOM API.
The DOM API allows us to dynamically change the style of an
element. This leads to powerful visual effects in an AJAX based
application.
Directly using the style attribute of the element.
By defining a style rule in a style sheet.
The latter allows us to change the look of all elements for which
the rule applies.
Style Rule
The most common style rule is class definition. A set of styles are defined for a
class. The class name is set for an element using its class attribute.
<style type="text/css" title="Basic Styles">
p.note {
color: red;
background: yellow;
font-weight: bold;
}
</style>
<p class="note">This is p.note</p>
6-17
17
Example
Styles defined for rules in a stylesheet
<style type="text/css" title="Basic Styles">
h2 {
font-size: 110%;
Rule 1
color: red;
background: white;
}
p.note {
color: red;
Rule 2
background: yellow;
font-weight: bold;
}
</style>
6-18
18
var s = element.style;
More on selectors and import rules will come in a latter chapter. For now, just
think of the class name selector that we have see in the previous slide. CSS2
allows for more complex selectors. A selector is eventually used to determine
which elements will be eligible for a particular rule. System will apply the rule's
style to these elements.
6-19
19
6-20
This will wipe out all other styles and only set these styles. Generally, this is not
recommended, but may be faster than setting many styles separately.
When setting coordinate and size attributes, make sure that you specify the
unit.
element.style.top = "100px"; //This will work
element.style.top = "100"; //This will not work and will be ignored
6-21
21
6-22
22
IE Example
sheet.addRule("h2", "font-size: 110%; color: red; background: white;");
sheet.addRule("h2", "font-size: 110%; color: red; background: white;", 0);
//Insert at the top
Mozilla Example
sheet.insertRule("h2 {font-size: 110%; color: red; background: white;}", 0);
6-23
23
var rules;
if (sheet.rules) {
rules = sheet.rules; //IE
} else {
rules = sheet.cssRules; //Mozilla
}
for (var k = 0; k < rules.length; ++k) {
rule = rules[k];
if (rule.selectorText == "p.note") {
rule.style.backgroundColor = "green";
}
}
6-24
24
Each data type has a set of properties, events and methods. We will discuss
the most common HTML data types in this chapter.
All HTML data types inherit from the Element object which we have already
discussed in a previous chapter.
var t = document.createElement("table");
var row = t.insertRow(0); //returns a HTMLTableRow object
Using the DOM HTML API, you can dynamically add, remove or
manipulate a page and create a feature rich application.
You don't explicitly use the data type name in JavaScript. For example, this will
not work:
var t = new HTMLTableElement(); //Will not work
var t = document.createElement("table"); //This will work
//More example
var s = document.createElement("select"); //Returns a HTMLSelectElement
object
6-25
25
These elements inherit all the methods and properties of the Element object. A
table can be looked up from a document like any other element (that is, by
calling getElementById()).
6-26
26
The HTMLTableElement
Object
Key properties:
Key methods:
6-27
The HTMLTableRowElement
Object
Key properties:
Key methods:
6-28
The HTMLTableCellElement
Object
Key properties:
6-29
6-30
30
6-31
Key properties:
Methods:
6-32
32
The HTMLInputElement
Object
A large number of input control types are created using the <input>
element.
Key properties:
Key methods:
6-33
The HTMLSelectElement
Object
Key properties:
Methods:
Examples
//Delete all options in a drop down list
var countrySelect = document.getElementById("country");
//Clear options
while (countrySelect.options.length > 0) {
countrySelect.remove(0);
}
//Add a new country option
var option = document.createElement("option");
option.text = "Canada";
option.value = "CA";
try {
countrySelect.add(option, null);
} catch (e) {
//IE
countrySelect.add(option);
}
6-34
34
The HTMLOptionElement
Element
Key properties:
6-35
Review Questions
1.
2.
3.
4.
5.
6-36
Review Questions
6.
7.
6-37
Review Answers
1.
2.
6-38
Review Answers
3.
4.
5.
Style rules
False. It affects the look of all elements for
which that rule applies.
6-39
Review Answers
6.
7.
6-40
7-1
Introduction
7-2
Application layer protocol deals with the data format of the communication.
This is also known as the Remote Procedure Call (RPC) mechanism. In
this mechanism, the client invokes a specific operation or method of the
server side application. For example, placeOrder or cancelOrder. An
operation may take any number of input parameter data. As a result, a
typical request contains the following information:
1. The operation name that should be invoked.
2. The input data (Optional).
3. User's identifier (Optional).
The operation may return data back.
7-3
Server
Application Layer
(XML, DWR, SOAP, JSON)
Application Layer
(XML, DWR, SOAP, JSON)
Presentation Layer
(HTTP)
Presentation Layer
(HTTP)
Session, Transport,
Network Layer etc.
(TCP/IP)
Session, Transport,
Network Layer etc.
(TCP/IP)
7-4
7-5
7-6
Advantages:
Disadvantages:
7-7
XML Document
The client can iterate through the DOM document and display
data from various elements in the document inside various
elements in the page.
An example of an XML document returned by the server is
shown below.
Example
Let us say that the server returns a list of past orders placed by the user as the
following XML document:
<order_list>
<order id="10001" date="10/10/2005" status="SHIPPED"/>
<order id="10053" date="11/9/2005" status="PENDING"/>
</order_list>
The client code will need to iterate through all <order> elements and show
various properties of the order in a table cell.
7-8
7-9
The example above shows how to create a DOM document for the
order list in the server side. Next, we will learn how to write the
document in the HTTP reply stream.
7-10
7-11
7-12
7-13
Here we see the Page_Load() method of a codebehind class. First, it sets the
content type of the reply to "application/xml". Next, it calls the WriteOrderXML
method that we have developed in the previous slide. Notice, that, as the
Stream object it supplies the HTTP reply stream. This causes the
WriteOrderXML function to directly write the XML to the HTTP reply. This is
one of the most efficient ways to output a large XML to the browser.
7-14
The example below shows each order using a <p> tag inside of a <div> tag
with id "result".
function handleReply(r) {
var doc = r.responseXML;
var order_list = doc.documentElement;
var orders = order_list.childNodes;
var theDiv = document.getElementById("result");
for (var i = 0; i < orders.length; ++i) {
var order = orders[i];
var text;
text = "<b>ID:</b> " + order.getAttribute("id") +
" <b>Placed on:</b> " + order.getAttribute("date") +
" <b>Status:</b> " + order.getAttribute("status");
var p = document.createElement("p");
p.innerHTML = text;
theDiv.appendChild(p);
}
}
7-15
In the current case, we use the API to navigate the XML document
returned by the server.
7-16
Methods:
7-17
Methods:
Node Types
Almost everything in a DOM document (including the document itself) is a
node. Each node is a leaf in the tree like structure that a DOM document is.
For example, the attributes of an element are also nodes. If an element has
body text, it is represented by one or more text nodes. Common node types
are:
1 A regular element. nodeValue is null.
2 Attribute. nodeValue is the value of the attribute.
3 Body text of an element. nodeValue is the text contained by this node.
7-18
The number of text nodes and how the body text will be chunked up
between them is totally dependent on the browser and the amount of body
text.
<comments>
nodeType: 1
<comments>
Hello fantastic world!
</comments>
nodeValue: world!
nodeType: 3
7-19
The example above shows how to set the body text of an element in chunks.
We didn't have to create two separate text nodes. Certainly, the following will
have the same effect:
var txt = document.createTextNode("Hello fantastic world!");
e.appendChild(txt);
7-20
In the example above, we are showing the body text of the <comments>
element using a <textarea> element.
Note, here the "doc" variable represents the DOM document returned by the
server. The "document" variable represents the XHTML document rendered as
a page by the browser.
We iterate through all the children nodes of the "comments" element. If the
nodeType of a child is 3, it indicates a text node. For each text node, we create
a new text node and append it as a child of the <textarea> element.
Note: You may think of directly appending a text node from one document as
a child of an element in another document. For example:
if (n.nodeType == 3) {
ta.appendChild(n);
}
This works fine in FireFox but not in IE. Which is rather unfortunate. Since the
code above will work much faster as we are not creating new text nodes.
7-21
The latter uses a simple name value pair pattern. XML can allow for
a more sophisticated data structure.
The XML document will be sent using a HTTP POST request. The body will
look something like this:
xml=<order><item id="101" date="10/13/2006"></order>
7-22
Mozilla Example
var doc = document.implementation.createDocument("", "order_list", null);
var e = doc.createElement("order");
e.setAttribute("id", "101");
e.setAttribute("date", "10/13/2006");
doc.documentElement.appendChild(e);
e = doc.createElement("order");
e.setAttribute("id", "102");
e.setAttribute("date", "10/13/2006");
doc.documentElement.appendChild(e);
7-23
7-24
7-25
function getXMLString(doc) {
var xml = null;
try {
//Mozilla
var ser = new XMLSerializer();
xml = ser.serializeToString(doc);
} catch (e) {
//IE
xml = doc.xml;
}
return xml;
}
7-26
7-27
The example above shows how you can reconstruct the posted XML
document in the server side. First we retrieve the XML text by calling
request.getParameter. We then parse the text to create a DOM document
object.
7-28
Review Questions
1.
2.
3.
4.
5.
6.
7-29
Review Answers
1.
2.
7-30
Review Answers
3.
7-31
Review Answers
4.
5.
7-32
Review Answers
6.
7-33
8-1
Introduction
In the "basic" chapter we covered HTML and XML and formatted data
exchange.
Although powerful, the problem with XML is that, much code needs to be
written in client and server side to convert data into XML. For example,
when the server sends data to the client, Java objects need to be converted
to XML. Upon receiving the data, a client will need to navigate the XML
document to retrieve data.
8-2
8-3
JSON Syntax
{"id":10,"name":"J. Buchman","active":true}
JavaScript allows you to construct a new object by using the object literal
notation. For example:
var customer = {"id":10,"name":"J. Buchman","active":true};
A JSON string is simply a string formatted in that notation. For example:
{"id":10,"name":"J. Buchman","active":true}
Such a string can be exchanged between an AJAX client and server.
8-4
JSON Syntax
8-5
var customer =
eval( "(" + replyString + ")" );
document.getElementById("name").innerHTML =
customer.name;
In that case the server needs to convert the JSON string into
Java objects. JSON is used primarily with HTTP reply.
The client can send request data either as JSON string or as regular POST
data. The latter is easy and no special API is required in the server side. If the
client sends a JSON string, the server will need to use a JSON API to convert
the string into Java object.
8-6
Server Code
GET GetCustomer?id=10
{"id":10,"name":"J. Buchman","active":true}
The AJAX code in the browser sends a GET or POST request. The server
responds with a JSON string. The client code receives the JSON string and
constructs a JavaScript object by simply calling the eval() method.
8-7
8-8
All property fields must be public. Getter and setter methods are
optional.
8-9
8-10
function fetchCustomer() {
ajaxGet("GetCustomer?id=10", showResult);
}
function showResult(request) {
var customer = eval("(" + request.responseText + ")");
document.getElementById("result").innerHTML =
customer.name;
}
Notice, how the customer object has the same fields as the corresponding
Java class.
8-11
8-12
Once again, we evaluate the JSON string returned by the server. This time,
the evaluated object is an array.
8-13
Advanced JSONObject
Methods
8-14
Example:
JSONArray arr = new JSONArray();
HashMap map = new HashMap();
map.put("name", "Jack D.");
map.put("ID", new Integer(10));
arr.put(map);
map.put("name", "Mary M.");
map.put("ID", new Integer(11));
arr.put(map);
//Generate the JSONString
String jsonStr = arr.toString();
Now jsnStr will be:
[{"name":"Jack D.","ID":10},{"name":"Mary M.","ID":11}]
8-15
Summary
8-16
Review Questions
1.
2.
3.
4.
5.
6.
What is JSON?
How can you produce JSON using Java on the server
side?
When constructing a JSONObject, what 2
parameters must be supplied to the constructor?
When creating a model class using Java, what
restriction is placed on its fields?
How does the client convert a JSON string returned
by the server into a JavaScript object?
What is the advantage of the JSON approach over
the XML document approach?
8-17
Review Answers
1.
2.
3.
4.
8-18
Review Answers
5.
6.
8-19