↑
Main Page
Using iframes
window.onload = function () {
parent.frames[0].handleResponse(
document.forms[“formResponse”].result.value);
};
</script>
</head>
<body>
<form name=”formResponse”>
<textarea name=”result”>This is some data coming from the
server.</textarea>
</form>
</body>
</html>
The important part about this window is the
onload
event handler, which calls the
handleResponse()
function from the first frame, passing in the value contained in the
<textarea/>
element. It’s very
important that the
handleResponse()
function be called no matter what, even if there is an error, to
prevent the JavaScript in the main frame from hanging while waiting for a response.
The previous code shows data already inserted into the
<textarea/>
for illustrative purposes; in
reality, this data would be output by some server-side logic.
When the
getServerInfo()
function is called in the main frame, the request is sent through the hidden
frame, and the data is passed back through the
handleResponse()
function and is displayed in an
alert. This is obviously a very simplistic example, but it illustrates the basic idea. The added bonus is
that this form of client-server communication works in any browser that supports framesets and
JavaScript (including older browsers like Netscape Navigator 4.x).
Using iframes
The hidden frame method evolved with the introduction of iframes into HTML. An
iframe
is a frame that
can be inserted anywhere in an HTML document, completely disconnected from any frameset. With this
innovation, developers changed the hidden frame method to create hidden iframes on the fly for the
purpose of communicating with the server.
To make use of iframes, you must make some changes to the
getServerInfo()
function:
var oHiddenFrame = null;
function getServerInfo() {
if (oHiddenFrame == null) {
oHiddenFrame = document.createElement(“iframe”);
oHiddenFrame.name = “hiddenFrame”;
oHiddenFrame.id = “hiddenFrame”;
oHiddenFrame.style.height = “0px”;
oHiddenFrame.style.width = “0px”;
oHiddenFrame.style.position = “absolute”;
oHiddenFrame.style.visibility = “hidden”;
document.body.appendChild(oHiddenFrame);
}
491
Client-Server Communication
19_579088 ch16.qxd 3/28/05 11:42 AM Page 491
Free JavaScript Editor
Ajax Editor
©
→