Chapter 19. JavaScript and Other Languages

CONTENTS

CONTENTS>>

  •  JavaScript and Java Applets
  •  A Little Java
  •  JavaScript and ColdFusion
  •  JavaScript and ASP.NET
  •  Summary

This chapter explores the relationship between JavaScript and other languages that you might encounter or want to learn more about. Each of these applications has its own unique relationship to JavaScript, and the role of JavaScript is an adjunct or facilitating one. None of them relies fundamentally on JavaScript, but they can be enhanced or in some way facilitated by JavaScript's capability to deal with different objects.

JavaScript and Java Applets

Java, while JavaScript's namesake, has very little in common with JavaScript other than some structures in the way that it is coded. Java is a compiled language, and because it is not interpreted in the browser as is HTML and JavaScript, it must be loaded into an HTML page to be viewed in a browser. Like a graphic or SWF file, Java programs, called "applets" (little applications), can be placed anywhere in an HTML script. The following format is the general one to bring in a Java applet to an HTML page:

<applet code="appletName.class" name="anyName" width=w height=h> 

The width and height variables set a block reserved for the Java applet. Measured in pixels, the block can take up just enough space for the applet, or it can take up a larger chunk that will be blank around the applet.

JavaScript to Check for Java-Enabled Browsers

I'll come back to the HTML surrounding a Java applet, but first you should have a way to find whether your browser's Java is enabled. You can save yourself a good deal of time and frustration, as well as that of the viewer who looks at your pages, by using JavaScript to see if Java is enabled. If Java is not enabled, no Java applet can check for that because, if it is disabled, the applet won't run. Therefore, JavaScript is essential to determine whether the user (or designer) has her Java enabled in the browser.

The general JavaScript technique for determining whether a browser has Java enabled uses this method with the navigator property to generate a Boolean outcome:

javaEnabled() 

Hence, this line used in a conditional statement returns true or false:

navigator.javaEnabled() 

The following script demonstrates how the method can be used. (Try it out on your own browser with Java enabled and disabled.)

<html>  <head>  <title>Check Java Enabled</title>  <script language ="JavaScript">  var gottaJava="Your Java is enabled in your browser. Your Java applets are ready to  launch.";  var lackaJava="Java is not enabled and until you enable Java in your browser, none  of the Java applets will launch.";  function gotJava() {      alert(gottaJava)       }  function nadaJava() {      alert(lackaJava)       }  if(navigator.javaEnabled()) {             gotJava();       } else {            nadaJava();       }  </script>  </head>  <body>  The page is up.  </body>  </html>

Figure 19.1 shows what you can expect when your browser has Java enabled.

Figure 19.1. Using JavaScript to tell a user whether the browser has Java enabled can save a lot of frustration in looking at blank pages.

graphics/19fig01.gif

A Little Java

At this point, you will need a Java applet to see the role of JavaScript. You can find plenty of free Java applets on the web. For example, java.sun.com has lots of free applets. (Hint: Click on Applets, Freebie Applets). However, if you'd like to try a little Java yourself, follow this path:

Java.sun.com > Java Tutorial > Your First Cup of Java Win32|UNIX|Mac 

Be sure to click on Win32, UNIX, or Mac instead of the general Your First Cup of Java link. Download the Java 2 Platform, Standard edition, and the Developer's Kit (all free!). When you have gone through the tutorial, try out the following Java applet. First, write the source code in a text editor (such as Notepad or SimpleText). Save the file as tooEZ.java. Note the different versions for Windows PC and Macintosh.

Windows:

tooEZ.java
import java.applet.*;  import java.awt.*;  public class tooEZ extends Applet {       public void paint(Graphics g) {            g.drawString("Java is a bit more demanding than JavaScript.", 50, 25);             g.drawString("You will find it used on servers as well.", 80, 50);       }  } 

Macintosh:

tooEZ.java
import java.applet.Applet;  import java.awt.Graphics;  public class tooEZ extends Applet {       public void paint(Graphics g) {             g.drawString("Java is a bit more demanding than JavaScript.", 50, 25);              g.drawString("You will find it used on servers as well.", 80, 50);        }  } 

Compile the tooEZ.java file to generate the tooEZ.class file. The class file is the file that you load into an HTML page. The following HTML page will load your applet and show it on the screen:

<html>  <head>  <title>EZ Applet Loader</title>  </head>  <body bgcolor="powderblue">  <applet name="javaDaba" code="tooEZ.class" width=300 height=250>  </applet>  <h3>The Applet takes up space assigned in the applet tag.</h3>  </body>  </html>

Note that the applet does not have the same background color as the rest of the HTML page. All font and background colors have to be generated in the Java applet. Figure 19.2 shows what you should see on your screen.

Figure 19.2. The block occupied by the Java applet moves the HTML text lower on the screen.

graphics/19fig02.gif

JavaScript and Applets

When an applet is embedded in an HTML page, JavaScript can access it through an applets[] array in the Document object expressed as an element name or number. More importantly, JavaScript can address a Java applet's methods. Unfortunately, Netscape Navigator and Internet Explorer do not share a compatible way of dealing with Java or JavaScript in this context. Microsoft ActiveX is used to control applets in Internet Explorer, and LiveConnect is in charge in Netscape Navigator up to Version 4. Beginning with Version 6, Netscape changed the DOM so that the applets[] array does not access Java controls in the same way as NN4.x. So, the following discussion will focus on using NN4.x with JavaScript and Java objects in an HTML page. As tested, they ran on both NN4.7 and IE5.5.

Calling Java Applet Methods from JavaScript

To see how JavaScript calls a Java applet's method, the next example makes a Java applet appear and disappear on the page. The two Java methods, hide() and show(), are standard methods of the Java Applet class. If you have applets that have their own methods, they can be called by JavaScript as well. These next two statements both call the applet named in the <applet> tag once by its name and once by its element value:

document.javaDaba.hide() 

and

document.applets[0].show() 

However, the two methods, hide() and show(), are not part of the JavaScript DOM and so are demonstrably methods belonging to Java. Figures 19.3 and 19.4 show two buttons firing JavaScript functions to make the Java applet disappear and then reappear.

Figure 19.3. The left button hides the Java applet by launching a JavaScript function.

graphics/19fig03.gif

Figure 19.4. The right button makes the hidden Java applet reappear.

graphics/19fig04.gif

jsJava.html
<html>  <head>  <title>Hide/Show Java</title>  <script language ="JavaScript">  function hideJava( ) {       document.javaDaba.hide( )        }  function showJava( ) {       document.applets[0].show( )        }  </script>  </head>  <body bgcolor="cornflowerblue">  <applet name="javaDaba" code="tooEZ.class" width=300 height=250>  </applet>  <form name="stealth">  <input type=button value="Hide Java Applet" onClick="hideJava( )";>  <input type=button value="Show Java Applet" onClick="showJava( )";>  </form>  </body>  </html>

Many of the Java applets that were necessary for dynamic web pages have been replaced to some degree by newer applications of both JavaScript and animation programs that generate SWF files (such as Flash and LiveMotion). The fact that Java files are compiled and not interpreted by the browser did not diminish the fact that they had to be sent across the web, slowing down larger files. As a result, much of the Java programming has migrated to servers where Java "servelets" can effectively deal with server-side tasks.

JavaScript and ColdFusion

In Chapters 14 19, different types of server-side or database applications were viewed working with JavaScript. JavaScript's main role was that of a preprocessor in a client-side environment. Another popular server-side program is one from Macromedia called ColdFusion. Like PHP, CGI, and ASP, ColdFusion works only with a special server that processes its code. However, unlike the other server-side languages discussed so far, ColdFusion has some JavaScript keywords that it adds to the JavaScript lexicon when used in a CF context. The keywords, however, are designed to work exclusively with CF and do not have a wider application.

If you decide to take up ColdFusion, you will be happy to learn that much of the server-side scripting is done in JavaScript. Unlike some of the other middleware examined in this book, JavaScript plays a server-side role in ColdFusion as well as a client-side role. The SQL commands will look virtually identical to MySQL and the SQL statements used in ASP pages.

Two JavaScript objects, WddxSerializer and WddxRecordset, are included in Cold-Fusion, each with several functions (methods). In the next sections, each of the objects is summarized along with each of the associated functions (methods).

WddxSerializer Object

As the name implies, this object contains functions to serialize JavaScript data structures. Serializing means that it generates a storable representation of a value. First, Web Distributed Data Exchange (WDDX) is a technology borrowed from XML. It facilitates complex data exchange between web programming languages (such as ColdFusion). So, a web site based in ColdFusion can share data with JavaScript. The data are translated into XML and then translated from XML into a language readable by ASP, PHP, or JavaScript. As you saw in Chapter 17, "Working with XML and JavaScript," JavaScript does not have a cross-platform XML interpreter. Internet Explorer uses ActiveX or document.all to bring data out of XML to the screen. What ColdFusion has done is add its own JavaScript object to make an equivalent transition. The only difference is that the WDDX technology facilitates the translation rather than ActiveX.

WddxSerializer supports four functions, but only the first, serialize( ), is likely to be used to any extent. The other can be used, but the data are more likely to be passed off using the serialize( ) function:

  • serialize(rootOjb) Creates a WDDX packet for the WddxRecordset object instance. On a server-side application, the following is a simple function to serialize the data:

    function getTheData(data,formAlpha) {       setSerial= new WddxSerializer( ); //define object        dataGroup= setSerial.serialize(data); //establish packet        if(dataGroup !=null) {             formAlpha.value=dataGroup;        }else{             alert("Data will not serialize")              }  } 
  • serializeVariable(name, obj) Serializes a property of a structure. When the object is not a date, Boolean, string, number, or array, it is treated as a structure.

  • serializeValue(obj) Serializes eligible data, which includes any JavaScript object, data, array, Boolean, number, string, or recordset.

  • write(string) Is an internal function not typically called. It appends data to a serialized data stream.

WddxRecordset Object

The WddxRecordset object includes several functions (methods)for construction of WDDX recordsets. Unlike the WddxSerializer, the WddxRecordset creates recordsets rather than serializes existing ones. However, one of the methods, wddxSerialize( ), does serialize a recordset of the WddxRecordset object.

  • addColumn(name) Adds a column to the recordset in a WddxRecordset instance. First the recordset is defined as an object in JavaScript, and then the addColumn( ) method adds a named column. The following script segment shows using this and other methods associated with the WddxRecordset object:

    customerSet= new WddxRecordset( );  customerSet.addColumn("salesDist");  customerSet.addRows(7);  customerSet.setField(2,"salesDist", distNum); 
  • addRows(number) Add the number of rows specified in the argument. Columns use names, and rows use numbers. Generally, the columns are fields and the rows represent records.

  • getField (row,col) Returns the element (not value) in a specified position indicated by the row number and column name.

  • getRowCount( ) Works something like a length method, but returns the number of rows rather than the number of items in an object or array or characters in a string.

  • setField(row,col,value) Specifies a value in a row number of a named column for example:

    customerSet.setField(4, "salesDistrict",7);

    This line would set the fifth row (the first is 0) of the column (field) named salesDistrict with the value of 7. The value 7 could have been a numeric or string variable as well.

  • wddxSerialize Serializes a recordset object.

While this book has emphasized client-side scripting with JavaScript, most of the same structures used on the client side can be used on the server side as well. As an added bonus, learning a new language such as ColdFusion is aided considerably by the fact that much of the script will be JavaScript.

JavaScript and ASP.NET

Microsoft's new .NET framework is a very different back end (if it indeed can be called that) than ASP. In fact, ASP.NET technology is not backward-compatible with ASP (see Chapter 15, "Using ASP with JavaScript"). The VB.NET scripting language has many similarities with VBScript, but that is due to the fact that VBScript has many similarities with Visual Basic, one of the core codes of ASP.NET. Included in ASP.NET codes, besides Visual Basic, are the following:

  • XML

  • CSS

  • HTML

  • DHTML

  • C++

  • C# (C-sharp)

At the time of this writing, ASP.NET was still in its infancy (beta), but it has generated a good deal of interest. However, at this stage, JavaScript does not seem applicable. The C# language was designed to be a friendlier version of Java, but it is compiled and so is not a substitute for JavaScript. A combination of C# and Visual Basic, though, might be seen as the best way of handling objects previously done by JavaScript. Working in an environment of web forms for developing code, it is difficult to discern what role, if any, is to be played by JavaScript. On one hand, JavaScript could play the same role in ASP.NET that it does with ASP: that of an input preprocessor. On the other hand, preprocessing may be done in the ASP.NET web form itself.

ASP.NET is not backward-compatible with ASP (or ASP pages written in VBScript), but this does not mean that it is or is not compatible with JavaScript. Because Microsoft has included DHTML as a code that works with ASP.NET, you might be led to believe that, within the DHTML, JavaScript would be welcomed, if as nothing more than a preprocessor.

Summary

JavaScript is a Jack-of-all-trades scripting language. It works well with HTML, DHTML, and most middleware languages such as PHP, CGI, and ASP. What's more, as seen in this chapter, JavaScript works with compiled languages such as Java to act as an event handler for methods and as a detector of a browser's capability to detect Java.

ColdFusion has integrated JavaScript into the heart of its language. Not only can ColdFusion server-side scripts include JavaScript, but ColdFusion has added keywords to the JavaScript lexicon for enhancing its role as a database middleman.

Microsoft's ASP.NET, on the other hand, might not have a role for JavaScript. At this stage of ASP.NET's development, it is difficult to say with certainty, but most of JavaScript's traditional functions have been solved with other coding options. Nevertheless, when JavaScript was first introduced, no one had any idea how key it would be come to the Internet, and ASP.NET could yet find it necessary and useful to work in a JavaScript environment.

CONTENTS


JavaScript Design
JavaScript Design
ISBN: 0735711674
EAN: 2147483647
Year: 2001
Pages: 25

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