11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Figure 19-1: Unlikely news from <strong>JavaScript</strong> Ref’s authors<br />

While it‘s clear you could achieve a similar effect using meta-refreshes or <strong>JavaScript</strong> redirects,<br />

the dynamic content approach doesn‘t require reloading the page and allows you to update<br />

multiple content areas independently from different sources. You just need to be careful to keep<br />

your naming consistent so the scripts returned by the server can access the appropriate parts<br />

of the page.<br />

Note Those familiar with <strong>JavaScript</strong>’s same origin policy (Chapter 22) might wonder if this<br />

technique would work if the RPC is made to a server other than that from which the<br />

document was fetched. <strong>The</strong> answer is yes, because externally linked scripts are not<br />

subject to the same origin policy.<br />

Cross-Site Scripting<br />

You need to be extremely careful to avoid cross-site scripting vulnerabilities when implementing<br />

dynamic content fetching. Chapter 22 has more information, but the basic idea is that if your<br />

server-side script takes query parameters and then writes them back out in the response<br />

without escaping them, an attacker could pass <strong>JavaScript</strong> in the URL, which would then be<br />

executed by the browser in the context of your site. For example, an attacker could construct a<br />

URL that includes <strong>JavaScript</strong> to steal users‘ cookies and then send spam out.<br />

Server-Side Computation<br />

<strong>The</strong> dynamic content approach isn‘t limited to fetching content; you can use it to carry out<br />

server-side computation that would be impossible (or at least very inconvenient) to do with<br />

<strong>JavaScript</strong>. As an example, suppose you wished to provide a spelling correction feature for a<br />

on your page. To include a dictionary and spelling-correction code in your script<br />

would be unwieldy at best, so the feature is better implemented via RPC to a server.<br />

<strong>The</strong> following example illustrates the basic concept. To keep things simple, this script only<br />

checks a single word entered in an , but you could extend it to check an entire<br />

. Notice how we use a variable to signal that the RPC is complete.<br />

<br />

<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!