Javascript by zhangyun

VIEWS: 17 PAGES: 80

									Client Side Programming

   Representation and Management
         of Data on the Web


                                   1
        Client-Server Architecture
• In a client-server architecture, computation is done
  either in the client or in the server
• There are cases where we can choose whether to
  perform the computation in the client or in the
  server
  – For example, transforming an XML document using XSL

• There are cases where we cannot choose where
  to perform the computation
  – For example, accessing a database
                                                          2
       Strengths and Weaknesses of
         Server-Side Computation
• Strengths                     • Weaknesses
  – allows access to server       – puts most of processing
    files and databases             load on server
  – makes no assumptions          – requires round-trip for
    about client computer           every submission, using
    capabilities, puts little       valuable bandwidth
    burden on it                  – cannot provide
  – easier to manage and            instantaneous response
    control on server               expected with GUI
  – more secure for client        – less secure for server
                                                              3
              Form Validation

• Consider the case where a user is required
 submit her name to a server application
• Where, for example, should we check that
 the inserted value is not an empty string?
  – In the client (i.e., the Web browser)?
  – In the server?


                                               4
            Client Side Technologies
• Javascript
   – Developed by Netscape
   – Supported by all browsers (although not all support the standard)
   – Very light (no graphics) and good interaction with HTML

• VBScript
   – Developed by Microsoft
   – Supported only by Microsoft Internet Explorer
   – A light version of Microsoft Visual Basic

• Java Applets
   – Developed by Sun
   – In the past it was supported by all browsers, but not any more
   – Capable of doing almost anything that Java allows
                                                                         5
              About Applets

• An Applet is a Java application, embedded
 in a Web page
  <APPLET CODE=“AppletClass” WIDTH=x HEIGHT=y/>

• When a browser loads the Web page, the
 applet byte-code is downloaded to the client
 box and executed by the browser
• Commonly used for: games, graphics, etc.
                                                  6
7
             Applets Limitations
• Security Restrictions: Applets cannot access files
  in the client computer nor files (or databases)
  behind a firewall
• The Bandwidth Problem: Applets are usually large
  in comparison to HTML files, thus , the download
  time becomes unacceptable
• Compatibility:
  – Client must have a compatible browser
  – Thin clients may not support the whole Java API
                                                       8
Javascript




             9
                    Overview
• A "scripting" language for HTML pages
• The code is embed in HTML pages
• The browser interprets and executes the script (it is
  not compiled)
• Do not declare data types for variables (loose
  typing)
• Dynamic binding – object references checked at
  runtime
                                                      10
             Overview (cont.)

• Scripts can manipulate "browser objects:"
  – HTML form elements
  – Images
  – Frames
  – etc.

• For security – cannot write to disk (when run
 on a client)
                                                  11
                  Abilities
• Generating HTML content dynamically
• Monitoring and responding to user events
• Validate forms before submission
• Manipulate HTTP cookies
• Interact with the frames and windows of the
  browser
• Customize pages to suit users
                                                12
                It is not Java

• Java :
  – compilation required (not a script)
  – can create “stand alone” application
  – object-oriented

• Why is it called Javascript then?



                                           13
  Web Architecture for JavaScript
  "CLIENT"                                           "SERVER"
Desktop access                                       Remote host
 Web browser
                                                        Web
                                                       (HTTP)
 HTML Page:      HTML/HTTP              HTML/HTTP
   <SCRIPT>                  Internet                  Server
                   TCP/IP                 TCP/IP
   …code..…
   </SCRIPT>




    built-in
  JavaScript
  interpreter                                         HTML
                                                     pages w/
                                                    embedded
                                                      script
                                         Why do we need
                    Example              <br> if we used
                                         writeln?
<HTML>
<HEAD><TITLE>An Hello World Example</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
 document.write("<font size='+4'>");
 document.writeln("Hello World!<br>");
 document.writeln("What a boring example</font>")
</SCRIPT>
</HEAD>
<BODY> <!-- An empty document body --> </BODY>
</HTML>
                                                           15
16
                    Example
<HTML>
<HEAD><TITLE>An Hello World Example</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
 document.write("<font size='+4'>");
 document.writeln("Hello World!<br>");
 document.writeln("What a boring example</font>")
</SCRIPT>
</HEAD>
<BODY> <h1>My Hello World Example</h1> </BODY>
</HTML>
                                                    17
18
                        Example
<HTML>
<HEAD><TITLE>An Hello World Example</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
 document.write("<font size='+4'>");
 document.writeln("Hello World!<br></font>");
</SCRIPT>
</HEAD>
<BODY> <h1>My Hello World Example</h1>
<SCRIPT LANGUAGE = "JavaScript">
 document.writeln("What a boring example")
</SCRIPT>
</BODY>
</HTML>
                                  What will happen?
                                                      19
  Some of Javascript Reserved
           Keywords
• break      • function • true
• case       • if       • typeof
• continue   • in       • var
• delete     • new      • void
• do         • null     • while
• else       • return   • with
• false      • switch
• for        • this
                                   20
Non Used Reserved Words

• catch      • extends
• class      • finally
• const      • import
• debugger   • super
• default    • try
• enum
• export
                          21
           Javascript Variables

• Untyped!
• Can be declared with var keyword:
  var foo;

• Can be created automatically by assigning a
  value:                  val has changed from an
                               int to a String!
  val = 1;
  val = “Thank for all the fish";
                                                    22
                Variables Names
• A variable name can be any valid identifier
• The identifier is a series of characters
   – Consisting of letters (lower and upper case), digits, and
     underscores (_)
   – Does not begin with a digit
   – Does not contain any space


• Javascript is case sensitive (foo and FOO are
  different)
                                                                 23
                       Variables
• Local variable is available only in the function
  where it is declared
• Global variable is available all over the document
• A variable declaration
   – Inside a function creates a local variable
   – Outside a function creates a global variable

• Local variables must be declared with var

                                                       24
                      Literals

• The typical bunch:
  – Numbers      17      123.45
  – Strings      “Let it be”
  – Boolean:     true       false
  – Arrays:      [1,“ab ba”,17.234]
  – null
                                  You can use typeof(A)
  – undefined                      to get the type of A:
                                  number, string, object..
      Arrays can hold anything!
                                                             25
                Operators

• Arithmetic, comparison, assignment, bit
 wise, Boolean (pretty much just like Java)


               + - * / % ++ --
               == != > < >= <=
              && || ! & | << >>
                += -= *= /= %=
                                              26
     The Special Plus Command

• Which of the following two is correct?
• What is the „type‟ of the answer?



         x = “The answer is” + 42
         y = 42 + “is the answer”



                                           27
            Which is correct?

• Which of the following two is correct?
• What is the „type‟ of the answer?



                x = "37" + 7
                y = "37" - 7



                                           28
             Types of Equality

• The equals == checks if both operands are
 equal after performing type conversion
• The equals === checks if both operands are
 of the same type and equal
• Example:
  – Is 3 == "3"   (true or false?)
  – Is 3 === "3" (true or false?)
                                               29
             Types of Inequality

• The equals != checks if both operands are
 unequal after performing type conversion
• The equals !== checks if both operands are
 not of the same type and or not equal
• Example:
  – Is 3 != "3"    (true or false?)
  – Is 3 !== "3"   (true or false?)
                                               30
             Conditional Operators
• equals
  if (a == b) {…}

• not equals
  if (a != b) {…}

• greater than or equal to
  if (a >= b) {...}

• less than or equal to
  if (a <= b) {...}
               Boolean Operators

• and
  if (true && true) {…}

• or
  if (true || false) {…}

• not
  if (! false) {...}
<HTML>
<HEAD><TITLE>Using Variables</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
  var firstNumber = 11,
     secondNumber = 23,
     sum;
  sum = firstNumber + secondNumber;
  document.write("<FONT COLOR = 'blue' SIZE = '6'>The sum
  of " + firstNumber + " and " + secondNumber + " is
  </FONT>");
  document.write(" <FONT COLOR = ‘red' SIZE = '7'>" + sum
  + "</FONT>");
</SCRIPT>
</HEAD>
<BODY> <!-- An empty document body --> </BODY>
                                                            33
</HTML>
34
           Control Structures

• Some just like Java:
             if     if-else      ?:   switch
                  for    while    do-while



• And a few not like in Java
                    for (var in object)
                        with (object)
                                               35
           JavaScript Constructs
• sequence (block)
  – executes with no conditions
  – semicolons optional using one statement per
    line, but not a bad thing to use all the time

  var metushelahAge = 130; var yourAverageAge
  yourAverageAge = metushelahAge - 98
  var myObject = new Object("initial value")
  more statements here..
  …..
              JavaScript Constructs
• condition (selection)
   if (condition) {statements if true}
   else {statements if false}


if (metushelahAge < yourAverageAge) {
       document.write ("<body><h2>its true that
       Metushelah is younger than most of you,")
       document.write ("<br>computers never lie!</h2>
        </body>")
   }
           JavaScript Constructs
• loop (iteration): both for and while loops are
  available

  for (var i=0; i < inputAge.length; i++) {
       var oneChar = inputAge.substring (i, i+1)
       if (oneChar < "0" || oneChar > "9") {
               alert("Please enter a valid number “
                       + oneChar + " is not valid.")
       }
   }
<HTML>
<HEAD><TITLE>Loops Example</TITLE>
<SCRIPT LANGUAGE = "JavaScript">


for (var counter = 1 ; counter <= 8 ; ++counter) {
    document.write(“<P><FONT COLOR = ‘blue’ SIZE = ‘
    “ + counter + “ '> Now with font size " + counter + "
    </FONT></P> “);
}
</SCRIPT>
</HEAD>
<BODY> <!-- An empty document body --> </BODY>
</HTML>                                                     39
40
          JavaScript Functions

• Functions are first class citizens
• The keyword function used to define a
  function (subroutine):


  function add(x,y) {
      return(x+y);

  }
                                          41
      Function Input and Outout

• Numbers and Boolean values always
 passed to functions using call-by-value
• For objects, a call-by-reference is used to
 pass them to the functions
• Numbers and Boolean values are always
 returned by value
• Objects returned by reference
                                                42
                 Example

• The next example uses functions to
 computing the Fibonacci numbers
• Note the use of recursion
• Be careful, some browsers may not deal well
 with very big numbers in the input (i.e., too
 many recursive calls)

                                                 43
44
<HTML>
<HEAD><TITLE>Functions Example</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function fibonacciValue() {
    var value = parseInt(document.fibonacciForm.number.value );
    window.status = "Calculating Fibonacci number for " + value;
    document.fibonacciForm.result.value = fibonacci(value);
    window.status = "Done Calculating Fibonacci number";
}
function fibonacci( n ) {
    if (n == 0 || n == 1) return n;
    else return fibonacci( n - 1 ) + fibonacci( n - 2 );
}
</SCRIPT></HEAD>                                                   45
<BODY>
<FORM NAME = "fibonacciForm">
<TABLE BORDER = "1" BGCOLOR = “fabbfc">
  <TR><TD BGCOLOR = “eabbfc">Enter a number</TD>
    <TD><INPUT NAME = "number" TYPE = "text"></TD>
   <TD><INPUT TYPE = "button" VALUE = "Calculate"
           ONCLICK = "fibonacciValue()"</TR>
  <TR><TD BGCOLOR = “fabbfc">Fibonacci Value</TD>
    <TD><INPUT NAME = "result" TYPE = "text"> </TD>
  </TR>
</TABLE>
</FORM>
</BODY>
</HTML>                                               46
          Function Arguments

• Within a function, its arguments can be
 accessed with arguments[i].
• The number of arguments is
 arguments.length
• A function can be created that takes any
 number of arguments

                                             47
                        Example
function myConcat(separator) {
     result="" // initialize list
     // iterate through arguments
     for (var i=1; i<arguments.length; i++) {
        result += arguments[i] + separator
     }
     return result
   }


//What does this return?
myConcat(", ","red","orange","blue")
                                                48
                Global Functions
• Javascript include several predefined functions that
  you can use
• For example,
  – eval(code-string) – gets a string of JavaScript
    code, evaluates it and executes it
     • It allows dynamic code execution

  – parseInt(string) – takes a string argument and
    converts its beginning to an integer number (or return
    NaN)
                                                             49
                   Objects

• Objects have attributes and methods
• There are pre-defined objects and user-
 defined object types
• Using objects has similarity to the syntax of
 C/Java:
           objectName.attributeName
            objectName.methodName()
                                                  50
 Objects Are Like Arrays

 myCar.make = "Ford"
 myCar.model = "Mustang"
 myCar.year = 66;




myCar[“make”] = "Ford"
myCar[“model”] = "Mustang"
myCar[“year”] = 66;
                             51
function show_props(obj, obj_name) {
   var result = ""
   for (var i in obj)
      result += obj_name + "." + i +
                 " = " + obj[i] + "\n"
   return result
}

     So, the function call
     show_props(myCar, "myCar")
     would return the following:


                       myCar.make = Ford
                       myCar.model = Mustang
                       myCar.year = 66
                                               52
         Creating a New Object

• There are two ways to create new objects:
• Object Initializer:
  – objectName={prop1:val1, …, propN:valN}

• Constructor Function:
  – define a constructor function
  – create the new object using new


                                              53
                 Example
function car(make, model, year) {
   this.make = make
   this.model = model
   this.year = year
}



theMazda = new car(“Mazda", “323", 1991)
theHonda = {make:”Honda”, year:1992,
            color:"red",wheels:4,
            engine:{cylinders:4,size:2.2}}

                                             54
           Creating a Method

• A method of an object is a function that has
 been assigned to the object:


    object.methodName = functionName




                                                 55
                Example
function displayCar() {
   var result = "A Beautiful " + this.year +
   " " + this.make + " " + this.model;
   document.writeln(result)
}
         function car(make, model, year) {
            this.make = make
            this.model = model
            this.year = year
            this.displayCar = displayCar
         }
             Setting the method
                                               56
             Eval Example
function stone(str) {
   eval("this."+str)
   this.y=43
   this["z"] = 44
}


flint = new stone("x=42")

document.write("<BR>flint.x is " + flint.x)
document.write("<BR>flint.y is " + flint.y)
document.write("<BR>flint.z is " + flint.z)

                                              57
           Deleting an Object

• To delete an object just set the object
 reference to null
• When are objects that are not set to null
 being removed?




                                              58
              Array Objects

• Arrays are supported as objects
• Attribute length
• Methods include:
    concat, join, pop, push, reverse,
    sort




                                        59
          Creating a New Array
• var a = [“red”, “blue”, “green”]
  – Allocates an array of 3 cells and initializes the
    values
• var b = new Array(5)
  – Allocates an array of 5 cells without initializing
    values
• var c = new Array()
  – Creates a new empty array
                                                         60
   Array Example Code


var a = [8,7,6,5];

for (i=0;i<a.length;i++)
    a[i] += 2;

b = a.reverse();


                           61
           Understanding Arrays
• Array literals:
   – arr1 = ["hello", 1, 33]

• Accessing arrays: (what is the result of)
   – document.writeln(arr1.length)
   – document.writeln(arr1[0])
   – document.writeln(arr1["abc"])
   – arr1[10]=66
   – document.writeln(arr1.length)

                                              62
     Passing Arrays to Functions

• Arrays can be passed to functions as
 arguments
• The array is passed by call-by-reference
• The name of the array is given to the
 function



                                             63
<HTML><HEAD><TITLE>Arrays Example</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function start() {
    var colors = ["red", "blue", "green"]
    printArray(colors);
    printArray(colors);
}
function printArray( arr) {
    for (var i in arr) {
        document.writeln("<FONT SIZE=5 COLOR=" + arr[i] + ">"
                      + arr[i] + " </FONT><BR>");
        arr[i] = "gray";
    }
}   </SCRIPT>
</HEAD><BODY ONLOAD = "start()"> </BODY></HTML>                 64
65
          Multidimentional Arrays

• var matrix = [ [0, 1, 1], [1, 1, 0], [0, 0, 0]];
• var myArray = [[1, 2, 3], [1], [1, 2]];
• Going over the array


   for (var i in myArray ) {
     for (var j in myArray[i])
      document.write(myArray[i][j]);

                                                     66
          Other Object Types

• String: manipulation methods
• Math: trig, log, random numbers
• Date: date conversions
• RegExp: regular expressions
• Number: limits, conversion to string



                                         67
            Math Common Methods
• abs(x)                    • cos(x)
• round(x)                  • sin(x)
• ceil(x)                   • tan(x)
• floor(x)                  • exp(x)
• max(x, y)                 • pow(x, y)
• min(x, y)                 • sqrt(x)
 Math Also includes         • log(x)
 constants
 such as: Math.E, Math.PI                 68
           String Common Methods
• charAt (index)              • slice(start, end)
• charCodeAt(index)           • split(string)
• concat(string)              • substr(start, length)
• fromCharCode(value1,
                              • substring(start, end)
  value2, …)
                              • toLowerCase()
• indexOf(substring, index)
                              • toUpperCase()
• lastIndexOf(substring,
  index)                      • toString()
                              • valueOf()
                                                        69
        Date Common Methods

• getDate(), getFullYear(), getMonth(), getDay
• getTime(), getHours(), getMinutes(),
 getSeconds(), getMilliseconds()




                                                 70
<HTML>
<HEAD><TITLE>Time Example</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function getTimes() {
    var current = new Date();
    var out = "Day: " + current.getDay()+"\n";
    out = out.concat("Month: " + current.getMonth() + "\n");
    out = out.concat("Year: " + current.getFullYear() + "\n");
    out = out.concat("GMT Time: " + current.toUTCString() +
    "\n");
    out = out.concat("Time: " + current.toString() + "\n");
    document.timesForm.output.value = out;
}
</SCRIPT>
</HEAD>                                                          71
<BODY>
<FORM NAME="timesForm">
<P>
<INPUT NAME = "getTimeButton" TYPE = "button"
  VALUE = "Get Time" ONCLICK = "getTimes()">
<P>
<TEXTAREA NAME = "output" ROWS ="10"
  COLS="42">
</TEXTAREA>
</FORM>
</BODY>
</HTML>                                         72
73
           Predefined Objects

• In JavaScript the following objects are
 automatically created for you (always
 available)
  – document
  – navigator
  – screen
  – window

                                            74
          The document Object

• Many attributes of the current document are
 available via the document object:
    title           cookie
    URL             images
    forms           links
    (fg/bg)Color    forms
                    and more …

                                                75
              Objects Hierarchy
• JavaScript objects include object hierarchy +
  (property or method)
   – window.document.lastModified
   – window.document.clear()
• need not be fully qualified
   – document.lastModified
• proceeds from most to least general
   – window.document.forms[0].inputText1.value
• all names are case sensitive
                                                  76
       Objects  Object Oriented
• Objects – complex data types or “containers” that
  have both data and code
• Methods – code or “functions” that work on an
  object‟s properties
• Properties – data that are stored and retrieved via
  object references
• This is not true "OO" because the object hierarchy
  is not extensible, you can create new objects, but
  cannot extend existing ones
                                                        77
          The with Statement

• Establishes the default object for a set of
  statements
• Within the set of statements, any property
  references that do not specify an object are
  assumed to be for the default object



                                                 78
           Example of with

var a, x, y
var r=10
with (Math) {
    a = PI * r * r
    x = r * cos(PI)
    y = r * sin(PI/2)
}
                             79
       Dynamic HTML


                  Java     Java
        CSS       Script   Script

HTML                       CSS
       HTML      HTML
                           HTML



         Dynamic HTML               80

								
To top