Handling JavaScript Sent from the Server


Sending the actual JavaScript back from the server for you to execute is a fairly common Ajax technique, and it’s used by many of the larger online APIs. However, I don’t really recommend this technique. There’s no real reason the server-side code should have to know the details of your client-side (browser-side, that is) code, and splitting things up this way can make your application harder to maintain and debug. But there certainly is one case where handling JavaScript sent to you from the server is unavoidable: when you’re dealing with a server-side API over which you have no control, like Google Suggest. In such a case, you have no choice: you have to be able to download and deal with JavaScript.

Returning JavaScript

You can see an example, javascript.html, in Figure 4.4. This example downloads JavaScript generated from a PHP script, javascript.php, and executes it.

image from book
Figure 4.4: Downloading JavaScript

When you click the button in this application, the code connects using Ajax to the server-side script javascript.php, and downloads the JavaScript to execute. In this case, the JavaScript to execute is simply a call to a function, display (which is already written in the Web page); here’s what javascript.php looks like:

 <?php     echo 'display()'; ?>

The application in the browser downloads the code to execute ('display()';) and executes it, calling the display function, which displays a message, as you can see in Figure 4.5.

image from book
Figure 4.5: Executing JavaScript

This application starts with the button you see in Figure 4.4:

 <body>   <H1>Reading JavaScript with Ajax</H1>   <form>     <input type = "button" value = "Get the JavaScript"       onclick = "getData('javascript.php')">   </form>   <div >     <p>The data will go here.</p>   </div> </body>

This button is connected to a JavaScript function named getData, and passes to that function the relative URL of the script to call on the server, javascript.php. Here’s how that function calls that PHP script:

 <html>   <head>     <title>Reading JavaScript with Ajax</title>     <script language = "javascript">       function getData(dataSource)       {         var XMLHttpRequestObject = false;         if (window.XMLHttpRequest) {           XMLHttpRequestObject = new XMLHttpRequest();         } else if (window.ActiveXObject) {           XMLHttpRequestObject = new             ActiveXObject("Microsoft.XMLHTTP");         }         if(XMLHttpRequestObject) {           XMLHttpRequestObject.open("GET", dataSource);           XMLHttpRequestObject.onreadystatechange = function()           {             if (XMLHttpRequestObject.readyState == 4 &&               XMLHttpRequestObject.status == 200) {                 .                 .                 .             }           }           XMLHttpRequestObject.send(null);         }       }         .         .         . 

The javascript.php script returns the text 'display()'; as you’ve seen:

 <?php     echo 'display()'; ?>

How can you execute this JavaScript? You can use the JavaScript eval function, which is designed to do exactly that: execute JavaScript that you pass to it in text form. In this case, you can simply pass the text returned from the server in the responseText property to the eval function:

 function getData(dataSource) {   var XMLHttpRequestObject = false;   if (window.XMLHttpRequest) {     XMLHttpRequestObject = new XMLHttpRequest();   } else if (window.ActiveXObject) {     XMLHttpRequestObject = new       ActiveXObject("Microsoft.XMLHTTP");   }   if(XMLHttpRequestObject) {     XMLHttpRequestObject.open("GET", dataSource);     XMLHttpRequestObject.onreadystatechange = function()     {       if (XMLHttpRequestObject.readyState == 4 &&         XMLHttpRequestObject.status == 200) {           eval(XMLHttpRequestObject.responseText);       }     }     XMLHttpRequestObject.send(null);   } }

This call to eval executes the JavaScript returned from the server, 'display();', which calls the display method. That method looks like this in the Web page javascript.html:

 function display() {   .   .   . }

In this function, you can display the message “It worked!” in a <div> element in the Web page like this:

 function display() {   var targetDiv = document.getElementById("targetDiv");   targetDiv.innerHTML = "It worked!"; }

And you can see the result in Figure 4.5. It does indeed work, thanks to the JavaScript eval function.

It turns out you can do more than just return JavaScript to execute. You can also return JavaScript objects from the server.

Returning JavaScript objects

So how can you return JavaScript objects from the server? Can you only return text and XML from the server? That’s correct, but you can actually format a JavaScript object as text, and convert it back to an object after you’ve downloaded it.

Here’s what that looks like in code. Say that you have a function named multiplier that accepts two operands, multiplies them, and displays the results in a <div> element:

 function multiplier(operand1, operand2) {   var product = operand1 * operand2;   var targetDiv = document.getElementById("targetDiv");   targetDiv.innerHTML = operand1 + " x " + operand2 + " = "     + product; }

Now say you wanted to create an object that holds the name of the function to call, multiplier, and the two operands to pass to that function; this is the kind of object a server-side program might pass back to you. In this case, the object being passed back to your script might have these three properties:

  • function: The function to call, multiplier

  • variable1: The first operand to pass to the multiplier function

  • variable2: The second operand to pass to the multiplier function

It’s easy enough to create an object with these three properties from text in JavaScript. Set up a variable named text to hold the text to use while creating the object, and create a variable named object to hold the object to be created, listing the setting for the three properties, function, variable1, and variable2:

 var text = "{function: 'multiplier', operand1: 2, operand2: 3};"; var object;

You can use the JavaScript eval function to create the new object and assign it to the object variable like this:

 eval('object = ' + text);

Then you can call the multiplier function using the data stored in the new object:

 <html>   <head>     <title>       Converting text to a JavaScript object     </title>     <script>       function convert()       {         var text = "{method: 'multiplier', operand1: 2, operand2:           3};";         var object;         eval('object = '+ text);         eval(object.method + '(' + object.operand1 + ',' +           object.operand2 + ');');       }       function multiplier(operand1, operand2)       {         var product = operand1 * operand2;         var targetDiv = document.getElementById("targetDiv");         targetDiv.innerHTML = operand1 + " x " + operand2 + " = "           + product;       }     </script>   </head>   <body>     <h1>       Converting text to a JavaScript object     </h1>     <form>       <input type = "button" value =         "Create JavaScript object from text"         onclick = "convert()">     </form>     <div >     </div>   </body> </html>

When the user clicks the button, the convert function is called, which creates the JavaScript object from text. Then the method, multiplier, is accessible by name like this: object.method, and the two operands, operand1 and operand2, are accessible as object.operand1 and object.operand2. So as you can see, you can indeed created (limited) objects from text, and of course in Ajax applications, that text can be downloaded from the server.

One well-known Ajax application online that sends you JavaScript to execute is Google Suggest, which is discussed next.



Ajax Bible
Ajax Bible
ISBN: 0470102632
EAN: 2147483647
Year: 2004
Pages: 169

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net