18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Client-Server Communication<br />

window.onload = function () {<br />

parent.frames[0].handleResponse(<br />

document.forms[“formResponse”].result.value);<br />

};<br />

<br />

<br />

<br />

<br />

This is some data coming from the<br />

server.<br />

<br />

<br />

<br />

The important part about this window is the onload event handler, which calls the handleResponse()<br />

function from the first frame, passing in the value contained in the element. It’s very<br />

important that the handleResponse() function be called no matter what, even if there is an error, to<br />

prevent the <strong>JavaScript</strong> in the main frame from hanging while waiting for a response.<br />

The previous code shows data already inserted into the for illustrative purposes; in<br />

reality, this data would be output by some server-side logic.<br />

When the getServerInfo() function is called in the main frame, the request is sent through the hidden<br />

frame, and the data is passed back through the handleResponse() function and is displayed in an<br />

alert. This is obviously a very simplistic example, but it illustrates the basic idea. The added bonus is<br />

that this form of client-server communication works in any browser that supports framesets and<br />

<strong>JavaScript</strong> (including older browsers like Netscape Navigator 4.x).<br />

Using iframes<br />

The hidden frame method evolved with the introduction of iframes into HTML. An iframe is a frame that<br />

can be inserted anywhere in an HTML document, completely disconnected from any frameset. With this<br />

innovation, developers changed the hidden frame method to create hidden iframes on the fly for the<br />

purpose of communicating with the server.<br />

To make use of iframes, you must make some changes to the getServerInfo() function:<br />

var oHiddenFrame = null;<br />

function getServerInfo() {<br />

if (oHiddenFrame == null) {<br />

oHiddenFrame = document.createElement(“iframe”);<br />

oHiddenFrame.name = “hiddenFrame”;<br />

oHiddenFrame.id = “hiddenFrame”;<br />

oHiddenFrame.style.height = “0px”;<br />

oHiddenFrame.style.width = “0px”;<br />

oHiddenFrame.style.position = “absolute”;<br />

oHiddenFrame.style.visibility = “hidden”;<br />

document.body.appendChild(oHiddenFrame);<br />

}<br />

491

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

Saved successfully!

Ooh no, something went wrong!