Title: Course Notes for CS1520 Programming Languages Part B By John C. Ramirez Department of Computer Science University of Pittsburgh
1Course Notes forCS1520 Programming
LanguagesPart BByJohn C. RamirezDepartment of
Computer ScienceUniversity of Pittsburgh
2- These notes are intended for use by students in
CS1520 at the University of Pittsburgh and no one
else - These notes are provided free of charge and may
not be sold in any shape or form - Material from these notes is obtained from
various sources, including, but not limited to,
the following - Programming the World Wide Web, multiple
editions, by Robert Sebesta (AW) - JavaScript by Don Gossein (Thomson Learning)
- https//developer.mozilla.org/en/JavaScript/Refere
nce - http//www.w3schools.com/jsref/default.asp
- http//www.w3.org/TR/XMLHttpRequest/
3Lecture 1 Intro to JavaScript
- What is JavaScript?
- Language developed by Netscape
- Primary purpose is for "client-end" processing of
HTML documents - JavaScript code is embedded within the html of a
document - An interpreter in the browser interprets the
JavaScript code when appropriate - Code typically allows for "preprocessing" of
forms and can add "dynamic content" to a Web page
4Lecture 1 JavaScript Basics
- How to include JavaScript in html?
- JavaScript programs require the ltSCRIPTgt tag in
.html files - ltscript type "text/javascript"gt
- ACTUAL JavaScript code here
- lt/scriptgt
- These can appear in either the ltHEADgt or ltBODYgt
section of an html document - Functions and code that may execute multiple
times is typically placed in the ltHEADgt - These are only interpreted when the relevant
function or event-handler are called
5Lecture 1 JavaScript Basics
- Code that needs to be executed only once, when
the document is first loaded is placed in the
ltBODYgt - Some browsers may not support scripting (i.e.
have it turned off) - To be safe, you could put your scripts in html
comments as specified in Sebesta text - This way browsers that do not recognize
JavaScript will look at the programs as comments - Note that, unlike PHP scripts, JavaScripts are
visible in the client browser - Since they are typically acting only on the
client, this is not a problem
6Lecture 1 JavaScript Basics
- However, if we want to prevent the script itself
from being (easily) seen, we can upload our
JavaScript from a file - This will show only the upload tag in our final
document, not the JavaScript from the file - Use the src option in the tag
- ltscript type "text/javascript" src
"bogus.js"gtlt/scriptgt - However, the source is likely still not really
hidden - In a temp folder somewhere on computer and can be
seen with a utility like FireBug - Thus you should not "hardcode" into Javascript
anything that you don't want the client to see
7Lecture 1 Simple Example
- ltHTMLgt
- ltHEADgt
- ltTITLEgtFirst JavaScript Examplelt/TITLEgt
- lt/HEADgt
- ltBODYgt
- ltH2gtThis line is straight HTMLlt/H2gt
- ltH3gt
- ltSCRIPT type "text/javascript"gt
- document.write("These lines are produced
byltbr/gt") - document.write("the JavaScript
programltbr/gt") - alert("Hey, JavaScript is fun!")
- lt/SCRIPTgt
- lt/H3gt
- ltH2gtMore straight HTMLlt/H2gt
- ltSCRIPT type "text/javascript"
src"bogus.js"gtlt/scriptgt - lt/BODYgt
- lt/HTMLgt
8Lecture 1 JavaScript Variables
- JavaScript variables have no types
- Type is determined dynamically, based on the
value stored - This is becoming familiar!
- The typeof operator can be used to check type of
a variable - Declarations are made using the var keyword
- Can be implicitly declared, but not advisable
- Declarations outside of any function are global
- Declarations within a function are local to that
function - Variables declared but not initialized have the
value undefined
9Lecture 1 JavaScript Variables
- Variable identifiers are similar to those in
other languages (ex Java) - Cannot use a keyword
- Must begin with a letter, , or _
- Followed by any sequence of letters, , _ or
digits - Case sensitive
10Lecture 1 JavaScript Expressions
- Numeric operators in JavaScript are similar to
those in most languages - , , , /, , , --
- Precedence and associativity are also fairly
standard - Strings
- Have the operator for concatenation
- Have a number of methods to do typical string
operations - charAt, indexOf, toLowerCase, substring
- Looks kind of like Java intentionally
11Lecture 1 JavaScript Expressions
- Similar to PHP, with mixed number/string type
expressions, JavaScript will coerce if it can - If operator is and an operand is string, it
will always coerce other to string - If operator is arithmetic, and string value can
be coerced to a number it will do so - If string is non-numeric, result is NaN
(NotaNumber) - We can also explicitly convert the string to a
number using parseInt and parseFloat - Again looks like Java
- See ex2.html
12Lecture 2 Control Statements
- Relational operators
- , !, lt, gt, lt, gt
- The above allow for type coercion. To prevent
coercion there is also - , !
- Similar to PHP
- Boolean operators
- , , !
- , are short-circuited (as in Java and PHP)
- Discuss
13Lecture 2 Control Statements
- Control statements similar to Java
- if, while, do, for, switch
- Variables declared in for loop header are global
to the rest of the script - Functions
- Similar to Java functions, but
- Header is somewhat different
- function name(param_list)
- Return type not specified (like PHP, since JS has
dynamic typing) - Param types also not specified
14Lecture 2 Functions
- Functions execute when they are called, just as
in any language - To allow this, function code should be in the
ltHEADgt section of the .html file - Variables declared in a function are local to the
function - Parameters are all value
- No parameter type-checking
- Numbers of formal and actual parameters do not
have to correspond - Extra actual parameters are ignored
- Extra formal parameters are undefined
- All actual parameters can be accessed regardless
of formal parameters by using the arguments array - See ex3.html
15Lecture 2 Array Objects
- More relaxed version of Java arrays
- Size can be changed and data can be mixed
- Cannot use arbitrary keys as with PHP arrays
- Creating arrays
- Using the new operator and a constructor with
multiple arguments - var A new Array("hello", 2, "you")
- Using the new operator and a constructor with a
single numeric argument - var B new Array(50)
- Using square brackets to make a literal
- var C "we", "can", 50, "mix", 3.5, "types"
16Lecture 2 Array Objects
- Array Length
- Like in Java, length is an attribute of all array
objects - However, in Javascript it does not necessarily
represent the number of items or even mem.
locations in the array - Unlike Java, length can be changed by the
programmer - Actual memory allocation is dynamic and occurs
when necessary - An array with length 1234 may in fact have
memory allocated for only a few elements - When accessed, empty elements are undefined
17Lecture 2 Array Objects
- Array Methods
- There are a number of predefined operations that
you can do with arrays - concat two arrays into one
- join array items into a single string (commas
between) - push, pop, shift, unshift
- Push and pop are a "right stack"
- Shift and unshift are a "left stack"
- sort
- Sort by default compares using alphabetical order
- To sort using numbers we pass in a comparison
function defining how the numbers will be
compared - reverse
- Reverse the items in an array
18Lecture 2 Array Objects
- These operations are invoked via method calls, in
an object-based way - Also many, such as sort and reverse are mutators,
affecting the array itself - JavaScript also has 2-dimensional arrays
- Created as arrays of arrays, but references are
not needed - see ex4.html
19Lecture 2 JavaScript Objects
- JavaScript is an object-based language
- It is NOT object-oriented
- It has and uses objects, but does not support
some features necessary for object-oriented
languages - Class inheritance and polymorphism not supported
- They can be faked but are not really there
- http//www.webreference.com/js/column79/
- http//www.webreference.com/js/column80/
20Lecture 2 JavaScript Objects
- JavaScript objects are actually represented as
property-value pairs - Actually similar to keyed arrays in PHP
- The object is analogous to the array, and the
properties are analogous to the keys - However, the property values can be data or
functions (methods) - Ex
- var my_tv new Object()
- my_tv.brand Samsung"
- my_tv.size 46
- my_tv.jacks new Object()
- my_tv.jacks.input 5
- my_tv.jacks.output 2
21Lecture 2 JavaScript Objects
- Note that the objects can be created and their
properties can be changed dynamically - Also, objects all have the same data type
object - We can write constructor functions for objects if
we'd like, but these do not create new data types
just easy ways of uniformly initializing
objects - function TV(brand, size, injacks, outjacks)
-
- this.brand brand
- this.size size
- this.jacks new Object()
- this.jacks.input injacks
- this.jacks.output outjacks
-
-
- var my_tv new TV(Samsung, 46, 5, 2)
22Lecture 2 JavaScript Objects
- Once an object is constructed, I can change its
properties if I want to - Lets say I want to add a method to my TV called
"show_properties" - function show_properties()
-
- document.write("Here is your TV ltBR/gt")
- document.write("Brand ", this.brand,"ltBR/gt")
- document.write("Size ", this.size, "ltBR/gt")
- document.write("Input Jacks ")
- document.write(this.jacks.input, "ltBR/gt")
- document.write("Output Jacks ")
- document.write(this.jacks.output, "ltBR/gt")
-
-
- my_tv.show show_properties
- See ex5.html
23Lecture 3 Javascript Objects
- We can do a lot with Javascript objects
- Even though Javascript is not truly
object-oriented, we can program in an
object-based way - Encapsulating data and methods within objects
- Utilizing methods for operations on the objects
- See ex6.html
- We will be using Javascript objects a lot with
client-side programming
24Lecture 3 Regular Expressions
- JavaScript regular expression handling is also
based on that in Perl - The patterns and matching procedures are the same
as in Perl, Java and PHP (PCRE) - However, now the functions are methods within a
string object (similar to Java) - var s "a man, a plan, a canal panama"
- var loc s.search(/plan/)
- var matches1 s.match(/an/g)
- var matches2 s.match(/\w/g)
- var matches3 s.split(/\W/)
- s s.replace(/\W/g, "-")
- Note that match is similar to the PHP match
function - Returns the matched pieces as opposed to the
non-matched pieces (that split returns) - See ex7.html
25Lecture 3 DOM
- The Document Object Model
- Developed by W3C (World-Wide Web Consortium)
- http//www.w3c.org/DOM/
- Specifies the contents of Web documents in an
object-oriented way - Allows programming languages to access and
manipulate the components of documents - Defined at a high level so that a variety of
languages can be used with it - It is still being updated / revised
- We are not even scratching the surface here
26Lecture 3 DOM
- History / Idea
- HTML and XML documents consist of tags
- Well-formatted documents (required in XHTML and
XML) can be viewed as a tree - Ex http//www.w3schools.com/htmldom/default.asp
- DOM provides a language-independent, object-based
model for accessing / modifying and adding to
these tags - DOM 0
- Not formally specified by W3C but includes a lot
of useful functionality
27Lecture 3 DOM
- DOM 1, 2, 3
- Formal specifications of model and functionality
- Each builds on / improves previous
- Unfortunately there are still compatibility
issues with browsers - IE through IE8 does not fully support DOM 2
- It has its own syntax for event attachment
- IE9 does support DOM 2 but until all older
versions go away the problem still exists
28Lecture 3 Events
- With documents DOM specifies events and event
handlers - Event model is similar to the one used in Java
- Different parts of a document have different
events associated with them - We can define handlers to react to these events
- These allow us to "interact" with and add
"dynamic content" to web documents - Ex Can preprocess form elements
- Ex Can load / update / change what is displayed
in response to an event
29Lecture 3 DOM and Events
- document refers to the top-level document
- Each document has access to its properties and to
the components that are declared within it - Ex title, URL, forms, applets, images
- Attributes with IDs can also be specified by ID
(from DOM 1) - Once we know the components, events and
event-handlers, we can write JavaScript programs
to process Web pages on the client-side - Client computers are typically less busy than
servers, so whatever we can do at the client will
be helpful overall
30Lecture 3 DOM and Events
- Ex Checking form correctness before it is
submitted - In HTML documents events are specified through
tag attributes - Within the tag identifying an HTML component, we
can specify in an attribute how the component
reacts to various events - See Sebesta Table 5.1 for events and tag
attributes and Table 5.2 for the tags that have a
given attribute - Similar in idea to Java, we assign event handling
code to the tag attributes, and the code executes
when the event occurs
31Lecture 3 Events
- We can also attach events in Javascript
- In DOM 0, events are attached in an inline way
- Ex theElement.onclick functionName
- In DOM 2, a more flexible event model was
developed, so that more than one handler could be
attached to the same event - Ex theElement.addEventListener(type, fn, opt)
- Where opt is a boolean to determine if the event
is captured or bubbles - See http//en.wikipedia.org/wiki/DOM_Events
- Unfortunately, IE (up through IE8) does not use
DOM 2 - It has its own, similar model
32Lecture 3 DOM and Events
- Ex Event mouseover occurs when the mouse is
place over a displayed element - Elements that allow for the mouseover event have
the attribute onmouseover - In HTML or Javascript, the programmer assigns a
function call to the attribute, so that when the
event occurs the function is called - ltinput type "radio" name "choice" value "1"
onmouseover "showChoice(1)"gt - We can define showChoice however we'd like
- ex alert("You are about to choose Choice 1")
33Lecture 3 Example Pre-processing a Form
- A very common client-side operation is
pre-processing a form - Ensure that fields are filled and formatted
correctly, so server does not have to - Saves load on the server, saves time and saves
bandwidth - We can check a form overall by using the
attribute onsubmit - We can put it right into the form as an attribute
- Or we can assign the attribute through the
document object in Javascript
34Lecture 3 Example Pre-processing a form
- We can check individual components as they are
entered as well - Ex ltinput type "text"gt has the onchange
attribute - Triggered when contents are changed and focus
changes - Ex ltinput type "radio"gt has the onclick
attribute - Triggered when the radio button is clicked with
the mouse - See ex8.html
- Note Script to process this form is not shown
- You may want to write it as an exercise
- Also note Firebug or Web Inspector use it if
you can!
35Lecture 3 Processing Multiple Forms and Multiple
Submits
- Web pages can also have multiple forms
- These can be handled both on the client side
using JavaScript and on the server side - Idea is to identify which form has been submitted
and respond accordingly - See mform.html and mform.php
- Similarly, we can have multiple submits of a
single form - See also msub.html and msub.php
- One more example demonstrating DOM
- See ex9.html
36Lecture 4 AJAX
- Asynchronous JavaScript And XML
- This is technique that was coined in Feb. 2005
but that has been used (more or less) for quite a
while before that - It allows the client and the server to
communicate without requiring a "hard" submit and
page refresh - In particular, the page can be updated without
reloading it in its entirety - Makes the user interface for a Web app. appear
more like that of a desktop app - See http//en.wikipedia.org/wiki/AJAX
- http//developer.mozilla.org/en/docs/AJAX
37Lecture 4 AJAX
- Let's look at a few details and some simple
examples - You may also want to research it on your own
- AJAX centers around the XMLHttpRequest object
- This object allows the client to connect to a
server and to respond to the reply once it has
become available - There is a lot that can be done with this,
especially in conjunction with XML and JSON we
will mention these later
38Lecture 4 AJAX
- It is a bit tricky to use, and is not consistent
across all browsers (esp. older versions) - However, once you get the hang of it, it can be a
very useful tool and it is REALLY COOL! - Basic Idea
- Programmer creates an instance of an
XMLHttpRequest object - Several useful attributes and methods are
associated with this object - see http//www.w3.org/TR/XMLHttpRequest/
- Let's look at a few of them to see how they work
together
39Lecture 4 AJAX
- onreadystatechange
- Attribute to which we assign an EventListener
(which is a function callback) - This will associate the function with the
occurrence of the readystatechange event - This event fires in several places, throughout
the the execution (each time the state changes) - We can check the readyState to see what, if
anything, we will do in response more on this
soon - open(method, url, async)
- Where "method" is an HTTP method
- Where "url" is the location of the server
- Where "async" is a boolean to determine if the
transfer is to be done asynchronously or not - Method to switch the object to the open state
i.e. get ready to send data to the server
40Lecture 4 AJAX
- send(data)
- Where "data" is a the information to be sent to
the server - Can be formatted in various ways, with different
encodings - Ex varvalue pair query string (like what you
see in the URL of a form submitted via GET) - Sends the data to the server, where (maybe) a
script may run and the response is sent back - readyState
- Attribute that stores the current state of the
object - Changes throughout the execution
- 0 ? uninitialized
- 1 ? loading
- 2 ? loaded
- 3 ? interactive
- 4 ? complete
41Lecture 4 AJAX
- status
- Did everything work correctly?
- 200 yes it did
- 404 Not found
- 500 internal server error
- For more codes, see
- http//www.w3.org/Protocols/rfc2616/rfc2616-sec10.
html - responseType
- What type of data did the server send back to the
client? - response, responseText, responseXML
- Get the data that was returned
- We can parse this to utilize the data to update
our page
42Lecture 4 AJAX
- Big Picture
- The XMLHttpRequest object enables us to interact
with the server "behind the scenes" and update
our web page accordingly - Server can still execute scripts as before (ex
PHP), but now it will send updates to the CURRENT
page rather than an entirely new page - Let's look at a simple example
- MozDemo.html from Mozilla devel. site
- Just demonstrates the basics of AJAX
43Lecture 4 AJAX
- Ok, that example was very simple
- In a real situation, the response from the server
will require us to update our local page,
possibly in a significant way - How to do this? document.writeln()?
- Only works during initial rendering of the page
- Using DOM? Yes!
- First we will look simply at HTML
- Later we will look at XML and possibly JSON
- See http//www.w3schools.com/htmldom/default.asp
- Idea If we treat our local Web page as an
object, then we can modify in response to data
sent back by the server
44Lecture 4 AJAX and DOM
- For example, consider the methods /attributes for
accessing/modifying data in an HTML table - First we need to get the table itself
- If we assign it an "id" attribute, we can use the
method getElementById() - We may then want a particular row
- We can use the rows array
- We may then want a specific cell
- We can use the cells array from the row
- And we may want to modify that cell
- We can use the innerHTML attribute
- Not true DOM see handout for another way
- See CDpoll.php and tabulate.php
45Lecture 4 AJAX and DOM
- However, what if we want to make more significant
changes? - Ex Add a new row to a table
- Get the table again
- Insert a new row
- Use insertRow()
- Insert a new cell
- Use insertCell()
- Add the data to the cell
- Use createTextNode() for text
- More complex for the radio button see handout
- Use appendChild()