7:40:00 PM

(0) Comments

Alternate Ajax Techniques, Part 1

design

By now, nearly everyone who works in web development has heard of the term Ajax, which is simply a term to describe client-server communication achieved without reloading the current page. Most articles on Ajax have focused on using XMLHttp as the means to achieving such communication, but Ajax techniques aren't limited to just XMLHttp. There are several other methods; we'll explore some of the more common ones in this series of articles.



Dynamic Script Loading

The first alternate Ajax technique is dynamic script loading. The concept is simple: create a new




The JavaScript file example1.js contains a single line:

callback("Hello world!");

When the button is clicked, the makeRequest() function is called, initiating the dynamic script loading. Since the newly loaded script is in context of the page, it can access and call the callback() function, which can do use the returned value as it pleases. This example works in any DOM-compliant browsers (Internet Explorer 5.0+, Safari, Firefox, and Opera 7.0+), try it for yourself or download the examples.

More Complex Communication

Sometimes you'll want to load a static JavaScript file from the server, as in the previous example, but sometimes you'll want to return data based on some sort of information. This introduces a level of complexity to dynamic script loading beyond the previous example.

First, you need a way to pass data to the server. This can be accomplished by attaching query string arguments to the JavaScript file URL. Of course, JavaScript files can't access query string information about themselves, so you'll need to use some sort of server-side logic to handle the request and output the correct JavaScript. Here's a function to help with the process:

function makeRequest(sUrl, oParams) {
for (sName in oParams) {
if (sUrl.indexOf("?") > -1) {
sUrl += "&";
} else {
sUrl += "?";
}
sUrl += encodeURIComponent(sName) + "=" + encodeURIComponent(oParams[sName]);
}

var oScript = document.createElement("script");
oScript.src = sUrl;
document.body.appendChild(oScript);
}

This function expects to be passed a URL for a JavaScript file and an object containing query string arguments. The query string is constructed inside of the function by iterating over the properties of this object. Then, the familiar dynamic script loading technique is used. This function can be called as follows:

var oParams = {
"param1": "value1",
"param2": "value2"
};
makeRequest("/path/to/myjs.php", oParams)




0 Responses to "Alternate Ajax Techniques, Part 1"

Post a Comment