• 【高级程序设计】Week2-4&Week3-1 JavaScript


    一、Javascript

    1. What is JS

    定义A scripting language used for client-side web development.
    作用

    an implementation of the ECMAScript standard

    defines the syntax/characteristics of the language and a basic set of commonly used objects such as Number, Date

    supported in browsers supports additional objects(Window, Frame, Form, DOM object)

    One Java

    Script?

    Different brands and/or different versions of browsers may support different implementations of JavaScript.

    – They are not fully compatible.

    – JScript is the Microsoft version of JavaScript.

    2. What can we do with JS

    Create an interactive user interface in a webpage (eg. menu, pop-up alerts, windows)

    Manipulate web content dynamically

    Change the content and style of an element

    Replace images on a page without page reload

    Hide/Show contents

    Generate HTML contents on the fly

    Form validation

    3. The lanuage and features

    ValidationValidating forms before sending to server.
    Dynamic writingClient-side language to manipulate all areas of the browser’s display, whereas servlets and PHPs run on server side.
    Dynamic typingInterpreted language (interpreter in browser): dynamic typing.
    Event-handlingEvent‐Driven Programming Model: event handlers.
    Scope and FunctionsHeavyweight regular expression capability
    Arrays and ObjectsFunctional object‐oriented language with prototypical inheritance (class free), which includes concepts of objects, arrays, prototypes

    4. Interpreting JS

    Commands are interpreted where they are found

    – start with tag, then functions in or in separate .js file

    static JavaScript is run before is loaded

    – output placed in HTML page

            • [document.write() ... dynamic scripting]

            •

    3. Dynamic Writing

    Document Object Model & Empty String
    • API for HTML and XML documents:
    -Provides structural representation of a document , so its content and visual presentation can be modified.
    -Connects web pages to scripts or programming languages.
    • Navigating to elements and accessing user input: textboxes , textareas ...
            Name text” name=“usrname”/>
            Email text” name=“usremail”/>
            button” onClick=“validate()” value=“Send”/>
    focus() and  modifying the value
    document.getElementById(“usrname").focus();
    d = document.getElementById(“usrname");
    if (d.value == “”)         d.value = “Please input!”;
    Modifying the HTML page to notify
    Name

    function validate() {
      var d = window.document.forms[0];
      if (d.usrname.value == “”)
         window.document.getElementById(“name”).innerHTML = “Enter”;
    }
    1. <html>
    2. <head>
    3. <script type=“text/javascript”>
    4. function validate() {
    5. if (document.forms[0].usrname.value==“”) {
    6. alert(“please enter name”);
    7. document.forms[0].usrname.focus();
    8. document.forms[0].usrname.value=“please enter name”;
    9. document.getElementById(“a”).innerHTML=“please enter name above”;
    10. }
    11. }
    12. script>
    13. head>
    14. <body>
    15. <font face=“arial”>
    16. <h1>Please enter detailsh1>
    17. <form>
    18. Name   <input type=“text” name=“usrname”> <br>
    19. <font color=“red”> <p id="a"> p>font>
    20. <font face=“arial”>
    21. Email   <input type=“text” name=“email”> <br><br>
    22. <input type=“button” value=“Send” onclick=“validate()”>
    23. form>
    24. body>
    25. html>

    五、 Arrays and Objects

    1. Strings & Intervals

    Useful string functions for validation
    if (ph.charAt(i)>=‘A’ && ph.charAt(i) <= ‘Z’)  // character at index i of this variable
    if (ph.length < 9) // the length of this variable
    if (ph.substring(0, 1) == ‘,’) // substring,  could first iterate through user input to extract all non-digits, then use substring to extract area code.
    if (ph.indexOf('@') == 0) //  index of character (charAt ) ,  emails never start with @
    setInterval()
            
                    DHTML Event Model - ONLOAD
            
            
            
                    

    Seconds you have spent viewing this page so far:

                     “soFar” STYLE = “font-weight: bold”> 0

    //文本连接
             
    Handling DelayssetTimeout()delay before execution
    setInterval()interval between execution
    clearInterval()
    clearTimeout()
    setTimeout(myFunc(), 1) delay 1 ms
    setTimeout(myFunc(),1000)delay 1 second
    myVar = setInterval(myFunc(), 1000)
    myVar = setInterval(myFunc(), 1000)

    2. JavaScript and Functions

    JavaScript functions are objectscan be stored in objects, arrays and variables
    can be passed as arguments or provided as return values
    can have methods (= function stored as property of an object)
    can be invoked
    call a function(Local call) directly: var x = square(4);
    (Callback) in response to something happening: called by the browser, not by developer’s code: events; page update function in Ajax

    3. Arrays and Objects

    Array Literal
    list = [“K”, “J”, “S”];
    var list = [“K”, 4, “S”]; // mixed array
    var emptyList = [];
    var myArray = new Array(length);
    // array constructor
    employee = new Array(3);
    employee[0] = “K”; employee[1] = “J”;
    employee[2] = “S”;
    document.write(employee[0]);
    new Object() / /A new blank object with no properties or methods.
    employee = new Object();
    employee[0] = “K”;
    var a = new Array();
    new Array(value0, value1, ...);
    employee = new Array(“K”, “J”, “S”);
    document.write(employee[0]);
    Sparse Arrays
    new Array();  // Length is 0 initially; automatically extends when new elements are initialised.
    employee = new Array();
    employee[5] = “J”; // length:  6
    employee[100] = “R”; //l ength :  101
    length is found as employee.length
    No array bounds errors.
    Associative array or object
    A = new Object();
    A["red"] = 127;
    A["green"] = 255;
    A["blue"] = 64;
    A = new Object();
    A.red = 127;
    A.green = 255;
    A.blue = 64;

       

    4. Scope and local functions

    1. html><head><title>Functions title>
    2. <script>
    3.         y = 6;
    4.         function square(x) {
    5.                 var y = x*x; // if didn’t include var, then y is the global y
    6.                 return y;
    7.         }
    8. script>head>
    9. <body>
    10. <script>
    11.         document.write(“The square of ” + y + “ is ”);//36
    12.         document.write(square(y));
    13.         document.write(“

      y is ” + y);//6

    14. script>
    15. body>html>
    JavaScript and ScopeClike languages have block scope:declare at first point of use
    JavaScript has function scope:variables defined within a function are visible everywhere in the function
    declare at the start/top of the function body.
    Inner functions can access actual parameters and variables (not copies) of their outer functions.

    六、Cookies

    作用
    allow you to store information between browser sessions, and
    you can set their expiry date
    默认browser session
    包含A name-value pair containing the actual data.
    An expiry date after which it is no longer valid.
    The domain and path of the server it should be sent to.
    Storing a cookie in a JavaScript program
    document.cookie = “version=” + 4;
    document.cookie = “version=” + encodeURIComponent(document.lastModified);
    • Stores the name-value pair for the browser session.
    • A cookie name cannot include semicolons,commas, or whitespace
    – Hence the use of encodeURIComponent(value) .
    – Must remember to decodeURIComponent() when reading the saved cookie.
    document.cookie = "version=" + encodeURIComponent(document.lastModified) +
    " ; max-age=" + (60*60*24*365);
    only the name-value pair is stored in the name-value list associated with  document.cookie .
    • Attributes are stored by the system.
    1. //A Cookie to remember the number of visits
    2. <html>
    3. <head>
    4. <title>How many times have you been here before?title>
    5. <script type="text/javascript">
    6. expireDate = new Date();
    7. expireDate.setMonth(expireDate.getMonth()+6);
    8. hitCt = parseInt(cookieVal("pageHit"));
    9. hitCt++;
    10. document.cookie= "pageHit=" + hitCt + ";expires=" + expireDate.toGMTString();
    11. function cookieVal(cookieName) {
    12. thisCookie = document.cookie.split("; ");
    13. for (i=0; ilength; i++) {
    14. if (cookieName == thisCookie[i].split("=")[0])
    15. return thisCookie[i].split("=")[1];
    16. }
    17. return 0;
    18. }
    19. script>
    20. head>
    21. <body bgcolor="#FFFFFF">
    22. <h2>
    23. <script language="Javascript" type="text/javascript">
    24. document.write("You have visited this page " + hitCt + " times.");
    25. script>
    26. h2>
    27. body>
    28. html>

    七、PROBLEMS WITH USER INPUT

    1. A Cautionary Tale: SQL Statements

    Enter phone number to retrieve address
    – ' ||'a'='a
    – No validation
    Name=value pair, PhoneNumber=‘||’a’=‘a, passed to serverServer side: access/update database information using SQL statements.
    SELECT * FROM table_name WHERE phone=‘parameter

    SELECT * FROM table_name WHERE phone=‘02078825555

    SELECT * FROM table_name WHERE phone=‘asdsdaEN3

    SELECT * FROM table_name WHERE phone=‘ ’||’a’=‘a
    • i.e. SELECT * FROM table_name WHERE phone=‘’ OR ‘a’=‘a’

    2. Further Examples of Event Handling

    Buttonssubmitting to, e.g. CGI: value=“Send”>
    onClick:
    Text BoxesonBlur=“typeNothing()”>
    When the document is first loaded
    or
    (inside