Five common Ajax patterns
|
|
It’s easy to see why so many Ajax application engineers prefer to use JavaScript code instead of
XML to encode the data. The JavaScript code is easier to read and manage as well as easier for the
browser to process.
With all this data-gathering and display, you see that the key to Ajax is the display of current data — the important part there being current. So, how do you ensure that you’re always getting fresh
data from the server?
Pattern 4. Avoiding browser cache
Browsers attempt to optimize Web traffic, so if you ask for the same URL twice, it’s likely that
rather than request the page again, your browser will simply use the page stored in the browser
cache. So, another common pattern in Ajax applications is the use of some randomizing element in
the URL to ensure that the browser doesn’t return a cached result.
My favorite technique is to add the numeric value of the current time to the URL. Listing 12 shows
this technique.
Listing 12. Pat4_cache.html
<html>
<script>
...
function loadUrl( url ) {
url = url + “?t=”+((new Date()).valueOf());
...
}
...
This is the code from Listing 1 but with the addition of some JavaScript text manipulation of the
URL string. I append to the URL a new parameter called t that has the value of the time. It doesn’t
really matter whether the server recognizes the value. It’s just a way to ensure that the browser
ignores its URL-based page cache.
Pattern 5. Replacing multiple HTML segments
The final pattern I demonstrate is an advanced version of the first pattern: the replacement of a <div> tag with content from the server. A common problem in Web applications is that in response
to user input, several areas of the display must be updated. For example, in a stock quote application,
one part of the display might show the most recent quote, while another portion of the display
shows a list of the most recent values.
To update multiple areas of the display, I use an XML response from the server that contains data
for both sections. Then, I use a regular expression to break out the individual sections from the
response. Listing 13 shows this technique. |
|
Apr 2008 | Java Jazz Up | 72 |
|
|
Pages:
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53 ,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63 ,
64,
65 ,
66 ,
67 ,
68 ,
69 ,
70,
71,
72,
73,
74,
75,
76,
77,
78,
Download PDF |
|
|
|