CS1520 Programming Languages Part B
CS1520 Programming Languages Part B
CS1520 Programming Languages Part B
CS1520
Programming Languages
Part B
By
John C. Ramirez
Department of Computer Science
University of Pittsburgh
1
• 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:
4 Programming the World Wide Web, multiple editions, by Robert Sebesta
(AW)
4 JavaScript by Don Gossein (Thomson Learning)
4 https://developer.mozilla.org/en/JavaScript/Reference
4 http://www.w3schools.com/jsref/default.asp
4 http://www.w3.org/TR/XMLHttpRequest/
2
Lecture 1: Intro to JavaScript
• What is JavaScript?
4 Language developed by Netscape
4 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
3
Lecture 1: JavaScript Basics
4
Lecture 1: JavaScript Basics
6
Lecture 1: Simple Example
<HTML>
<HEAD>
<TITLE>First JavaScript Example</TITLE>
</HEAD>
<BODY>
<H2>This line is straight HTML</H2>
<H3>
<SCRIPT type = "text/javascript">
document.write("These lines are produced by<br/>");
document.write("the JavaScript program<br/>");
alert("Hey, JavaScript is fun!");
</SCRIPT>
</H3>
<H2>More straight HTML</H2>
<SCRIPT type = "text/javascript" src="bogus.js"></script>
</BODY>
</HTML>
7
Lecture 1: JavaScript Variables
9
Lecture 1: JavaScript Expressions
10
Lecture 1: JavaScript Expressions
4 See ex2.html
11
Lecture 1: Control Statements
• Relational operators:
==, !=, <, >, <=, >=
• 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
12
Lecture 1: Control Statements
• Functions
4 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
13
Lecture 1: Functions
15
Lecture 1: Array Objects
4 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
16
Lecture 1: Array Objects
• Array Methods
4 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
17
Lecture 1: Array Objects
18
Lecture 1: JavaScript Objects
19
Lecture 1: JavaScript Objects
20
Lecture 1: JavaScript Objects
21
Lecture 1: JavaScript Objects
• Once an object is constructed, I can change its
properties if I want to
– Let’s say I want to add a method to my TV called
"show_properties"
function show_properties()
{
document.write("Here is your TV: <BR/>");
document.write("Brand: ", this.brand,"<BR/>");
document.write("Size: ", this.size, "<BR/>");
document.write("Input Jacks: ");
document.write(this.jacks.input, "<BR/>");
document.write("Output Jacks: ");
document.write(this.jacks.output, "<BR/>");
}
…
my_tv.show = show_properties;
– See ex5.html
22
Lecture 1: Javascript Objects
• History / Idea
4 HTML and XML documents consist of tags
4 Well-formatted documents (required in XHTML
and XML) can be viewed as a tree
• Ex: http://www.w3schools.com/htmldom/default.asp
4 DOM provides a language-independent, object-
based model for accessing / modifying and
adding to these tags
4 DOM 0
• Not formally specified by W3C but includes a lot
of useful functionality
26
Lecture 2: DOM
4 DOM 1, 2, 3
• Formal specifications of model and
functionality
• Each builds on / improves previous
4 DOM 4 is being finalized
4 With recent browsers there is general DOM
compatibility
• IE through IE8 does not fully support DOM 2
– It has its own syntax for event attachment
• So if client is using older IE some newer DOM
features may not work
27
Lecture 2: Events
31
Lecture 2: DOM and Events
32
Lecture 2: Example: Pre-processing a Form
33
Lecture 2: Example: Pre-processing a form
• 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!
34
Lecture 2: Processing Multiple Forms and Multiple Submits
38
Lecture 3: 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
39
Lecture 3: 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: var=value 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
40
Lecture 3: 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
41
Lecture 3: AJAX
4 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
• Show on board
4 Let's look at a simple example
• MozDemo.html – from Mozilla devel. site
– Just demonstrates the basics of AJAX
42
Lecture 3: AJAX
43
Lecture 3: AJAX and DOM
45
Lecture 3: AJAX and DOM
• Caution:
4 Be aware that AJAX can update data
locally and can cause inconsistency with
data at server
4 For example, consider 2 clients both running
CDpoll.php
• Client 1 then adds a new write-in choice
• Client 2 also adds a new write-in choice
– Both of these update the server DB, so any new
client will show them
– However, Client 1 will not show Client 2’s new
choice and vice-versa
46
Lecture 3: AJAX and DOM
4 So we need to either
• Get updates from as well as make updates to
the server with each connection
– But this may require a lot of work at each
connection
– See CDpoll2.php and tabulate2.php
• Design our program in such a way that we
only need to “sync” with the server
occasionally
– Updates from one client do not affect another
• Use the server to read from but not to write to
– Consistency is not a problem if data does not
change
47
Lecture 3: Updating the Page
49
Lecture 3: Updating the Page
50
Lecture 3: What about the “X”?
51
What about the X?
52
The X
4 See
• http://www.w3schools.com/xml/xml_dom.asp
• http://www.w3schools.com/xml/xml_server.asp
• Many others as well if you search the Web
53
The X
• Idea:
4 First we get the document
• var xmldoc =
httpReqObject.responseXML.documentElement
• Then we can access it via tags
var aTag =
xmldoc.getElementsByTagName(“tagname”)[0].childNodes[0].nodeValue
– Whew!
– What is this craziness?
– Basically it gets the data in the tag indicated
– Complexity allows for nested tags (remember that the
document is a tree)
» Note: Will be a lot easier with JQuery! Something to look
forward to!
54
The X
55
The X
57
The X
58
The X
4 See CDpoll-sortxml.php
59
XSLT
60
XSLT
61
JSON
62
JSON
• JSON
4 JavaScript Object Notation
• Data interchange format that allows text to
be converted into simple Javascript objects
(and back)
4 We can use this to send data from a server
to an AJAX client
• The client then generates Javascript primitive
objects by processing the text data
63
JSON
4 Idea:
• We can think of JS objects as a set of key /
value pairs
• Ex:
CD.id
CD.title
CD.artist
CD.votes
• We can then access the object as a single
entity, or we can access the individual
instance variables
64
JSON
65
JSON
66
JSON with JQuery
67
APIs
68
APIs
• See: http://www.programmableweb.com/category/all/apis
• Generally, accessing an API is
straightforward
4 Typically users must request access to the
API via a token or key
4 Individual requests send the key plus the
request details
4 Responses are sent back in some standard
format
• Ex: XML, JSON, etc
69
APIs
72
Client-Side Storage
73
Client-Side Storage
74
Client-Side Storage
• Is there an alternative?
4 With HTML 5 – yes!
4 We can now keep client-side data in a fashion
very similar to that of server-side data
4 We have two global variables that are
incorporated into our browser window and
which can be accessed / updated from our
scripts:
• sessionStorage
– Keeps data for current browser session (while
window or tab remains open)
75
Client-Side Storage
• localStorage
– Keeps data indefinitely
76
Client-Side Storage
4 Syntax:
• Both localStorage and sessionStorage can be
accessed as Javascript objects
• Functions which are of interest to us:
– setItem(key, value)
» Puts the value at the specified key
» Key and value must both be a string, but they could
be JSON (stringified objects)
77
Client-Side Storage
– getItem(key)
» Retrieve the value at the specified key
» If no value is there, it returns null
– removeItem(key)
» Remove the item at the given key
» Will be set back to null
– length
» Note that it is NOT a function – rather it is an attribute
value
» Returns the number of values stored in the storage
– key(index)
» Return the key at a given index
» Index values of keys are maintained in some sequential
way
» Thus, to get all keys in localStorage we can iterate the
the indexes from 0 to length
• For more info, see
https://developer.mozilla.org/en/DOM/Storage
78
Client-Side Storage
79