Java Scripting and XML

Embed Size (px)

Citation preview

  • 7/30/2019 Java Scripting and XML

    1/9

    JAVA SCRIPTINGJava script examples

    Javascript Example

    Note we can embed JavaScript code/instructions in the plain HTML code with the help of and tags. Inthe above example alert is the function/method of a predefined browser object that is, window object, and is used tocreate alert boxes or popup messages on the window. // is used in JavaScript to provide comments. Here, we use // sothat old browsers that do not support JavaScript treat information within the Script tag as comments.

    Writing on the page

    example-writing on the page

    Here, document is a browser object and write is its function which is used to write text on the page.Browser objects are loaded by a JavaScript capable browser to provide access to the web page and theHTML elements it contains. These objects are used to update and interact with the loaded web page.

    Operators in java scriptMathematical operators + For addition of two values - for subtraction of two values * for multiplication

    / for division % modulus (for calculating the remainder) ++ for increment -- for decrement Logical operators &&for logical and || for logical or ! for logical not

    Comparison operators== for Equal!= for not equal

    < for Less than for Greater than

    >= for Greater than equal

    Functions in javascriptA variable in JavaScript can be defined using the keyword var and a function by the Keyword function. A function can

    be defined in the following format: function myfunction() { // some code }

    Here, myfunction is the name of the function.

    Creating a calculator in JavaScript

    My Simple Calculator

    Add and Subtract Calculator

  • 7/30/2019 Java Scripting and XML

    2/9

    First Number:

    Second Number:

    In the above example, we have defined two functions, Addit () and minus() using JavaScript. With the help of an eventhandler onclick the control is shifted to any of the said functions and the code contained in the functions is accordinglyexecuted.For example, if a user adds no. 3 in the first text box and 9 in the second, then on clicking the button Add them!! theaddition of these two nos. would be displayed in an alert box due to the use of alert function in the code.

    To get the result in a text box, you need a slight change in the code contained in the functions Addit() and minus(), asshown below.

    My Simple Calculator

    Add Subtract Calculator

    First Number:

    Second Number:

    Result:

    We can also get the result of addition or subtraction written on a page using write function

    of the document object. Again we need to do a slight modification in the code as shown

    below.

  • 7/30/2019 Java Scripting and XML

    3/9

    parseFloat(num2)));}//-->

    First Number:

    Second Number:

    When a user types 3 and 9 in the two text boxes, respectively, as shown in Fig. 1 below and presses AddThem!! the

    addition of two nos. 12 is written on a web page (Fig. 2). On clicking Subtract Them!! the subtraction of two nos. -6is written on a page (Fig. 3). Note that in the brackets of document.write we concatenate or join some text information

    called string (within double quotation marks) with the addition/subtraction of two nos. using + sign. Theaddition/subtraction of nos. is achieved using function parseFloat(), that is, a function of predefined global object.

    Multiply and divide calculatorSee the following code:

    Multiply and Divide Calculator

    First Number:

    Second Number:

    Example - A Drop-Down List of Links

    A Drop-Down List of Links

  • 7/30/2019 Java Scripting and XML

    4/9

    Select a page previously done --->CalculatorStyle SheetWeb Forms

    Table MarginsFrames

    In the above example, event handler onchange has been used, having the effect that when an option is selected by theuser the control is shifted to the above defined function GoToIt(list). Due to the key word this information/list containedin the select tag is available to the argument list of the function GoToIt(). When the function would be executed the

    value of the selected option would be assigned to the variable selection. Due to location.href=selection, the existinglocation of the web page is changed to the location of

    the option/web page that has been selected and that particular web page opens. Location is another predefined browserobject.

    Example - If StatementIF statement in programming is used to alter the course of execution of code depending upon the value of a condition. See

    the following example:

    First Number:

    Second Number:

    For LOOPWhen we want some action to take place repeatedly till a particular point, we can apply a for loop. General format is:

    for(initializationStatement;condition;updateStatement){statements}.

    The code goes on executing itself till a certain condition is met.

    Example

    Using the For Statement

  • 7/30/2019 Java Scripting and XML

    5/9

    parseFloat(string) that parses the string as a floating point number, is the e xample of a function/method of GlobalObject. Note a general difference between properties and functions of an object in that the names of the properties are notfollowed by small brackets whereas the names of the functions do have small brackets following their names. Informationcontained in the small brackets of a function is called arguments. Also note that generally properties and functions of an

    object are invoked/referenced by typing the name of the object followed by a dot before typing the property or functionname, e.g, document.write().

    Array Object also has different properties and functions. Length is an important property of this objectthat identifies the length of the array. Its methods/functions include

    toString(), reverse(), sort() etc.Array ExampleUsing Arrays

    Using Arrays

    Math object provides a standard library of mathematical constants and functions. Following example shows some

    properties and methods of this object.

    Using the Math object

    Using the Math object

    Example Date object Writing the Current Date and Time Result is shown in Fig. 1 below. Here, Date() is the constructor of the date objectwhichprovides current date of the system.

    Getting date and time in a user friendly formatTo get the date/time in a different format, an instance of the date object can be created. In the following

    exampled is such an instance. To define the instance d of the date object we have to use a constructor ofthe date object, preceded by the word new. Constructor is defined as the initializing function used to create instance/copy of an object. It is after the name of the object whose constructor it is. Note that we

    can invoke or apply different methods/functions of the date object using this instance d, e.g, d.getDay(),d.getYear() etc.

    Example - Current Date and Time

  • 7/30/2019 Java Scripting and XML

    6/9

    += " " if (monthValue == 0)dateText += "January" if (monthValue == 1) dateText += "February" if (monthValue == 2) dateText +="March" if (monthValue == 3) dateText += "April" if (monthValue == 4) dateText += "May" if(monthValue == 5) dateText += "June"

    if (monthValue == 6) dateText += "July" if (monthValue == 7) dateText += "August" if (monthValue ==8) dateText += "September" if (monthValue == 9) dateText += "October" if (monthValue == 10)dateText += "November" if (monthValue == 11) dateText += "December"// Get the current year; if it's before 2000, add 1900 if (d.getYear() < 2000) dateText += " " +d.getDate() + ", " + (1900 + d.getYear()) else

    dateText += " " + d.getDate() + ", " + (d.getYear()) // Get the current minutes minuteValue =d.getMinutes() if (minuteValue < 10)minuteValue = "0" + minuteValue // Get the current hours hourValue = d.getHours() // Customizethe greeting based on the current hours if (hourValue < 12){

    greeting = "Good morning!"timeText = " at " + hourValue + ":" + minuteValue + " AM"

    }else if (hourValue == 12) { greeting = "Good afternoon!" timeText = " at " + hourValue + ":" +minuteValue + " PM" }

    else if (hourValue < 17) { greeting = "Good afternoon!" timeText = " at " + (hourValue-12) + ":" +minuteValue + " PM" }

    else { greeting = "Good evening!" timeText = " at " + (hourValue-12) + ":" + minuteValue + " PM" }// Write the greeting, the date, and the time to the page document.write(greeting + " It's " + dateText +timeText) //--> Result is shown in Fig. 2 below. Note that mainlythree variables, greeting, dateText and timeText have been used. Also, a number of if statements have beenused in order to get customized values.

    Example - String Object

    In the following example, str and myArray are the instances of string and array objects, respectively. The size of the array is 10. Here, charAt() is the function/method of string object. So, charAt(3) would providethe value of the element at the index three. Different other functions of string object have also been used.

    In the example, str.Split(' ') splits the string on the basis of blank space. After splitting, we assign parts ofthe string as values for the array. Using the String object

    Using the String object

    Using java script for applying for checks in a registration formWe can use JavaScript for applying different checks on a web form including pattern checking. Consider following

    example in this behalf, where we use a JavaScript function checkValues ():

  • 7/30/2019 Java Scripting and XML

    7/9

    return true;}//--> To Register Please Enter The Following Information:

    Name:

    Address:

    Login:

  • 7/30/2019 Java Scripting and XML

    8/9

    XML differs from HTML in two important respects. Firstly, XML is not a markup language with defined tags; rather, one

    can create ones own set of tags in XML. Secondly, XML tags do not provide information how text would appear on aweb page. Instead of that XML tags convey meaning of information included within them. To understand thesedistinctions consider the example of planets list again. Following is theXML code for that:

    36 million miles None176 days

    67 million miles None117 days

    93 million miles One

    24 Hours

    First line of the code is a declaration that it is an XML document (version 1). Second and last lines of the code are calledroot element tags. We enclose other elements within the root element tags. We assign a name to the root element that bestdescribes the purpose of our file. Other elements are called child elements. Thus, planet is a child element of planetlist.Further, each property of a planet is the child element of the planet element. So, distance, moons and daylength are thechild elements of planet element. Name is the attribute of the planet element. Names of child elements can be different

    between two organizations, which can make the sharing of information difficult. For instance, some may describe theproperty of a planet as Day and others may use the word Daylength for that purpose. This has led to the necessity of

    having uniform standards for writing different types of XML documents. Many companies have agreed to follow commonstandards for XML tags. A file that uses XML tags is called data type definition (DTD) or XML schema. Different DTDsare available for different industries. We now have accounting information, legal information standards etc.

    Rules for writing an XML code-All elements must be properly nested content-All attribute values must be quoted -All elements with empty content must be identified by ending in />
    ,

    All elements must be cased consistently must not be closed as Certain characters having reserved meanings cannot be used e.g, & , < etc.

    Embedding XML into HTML documents

    element can be used anywhere within HTML document to enclose XML content.

    See the following example in this regard:

    XML-example

    HTML text here

    spicy

    Also, element can be used for such purpose e.g.,

    Extensible Style sheet Language (XSL)

    XML files are translated using another file which contains formatting instructions. Formatting instructions are oftenwritten in Extensible Style sheet Language (XSL).

  • 7/30/2019 Java Scripting and XML

    9/9

    These formatting instructions are read over by special programsusually these programs are written in Java programminglanguage- called XML Parsers. Following diagram (Fig. 4) explains how web server might process http request for anXML page.

    We write XSL rules that match various xml elements. For that consider the following example:

    XML code Switch A very efficient device

    Rs. 1000. XSL code

    We can provide the formatting instructions for the above XML code by writing an XSL code as given below:


    Note that we use elements and in our XSL code to provide formatting instructions for the

    corresponding XML elements.

    HTML and XML editorsGeneral purpose text-editors for HTML are Notepad, Wordpad etc. However, there are certain HTML editors that help

    create web pages more easily, e.g., Macromedia Dreamweaver and Microsoft FrontPage.XML code can also be written in any general purpose text editor. However, there are special programs such as Epic

    Editor, TurboXML which can facilitate the editing job considerably.