JavaScript - WordPress.com

advertisement
INT222
Internet I - Internet Fundamentals
Week 1
Outline
•
•
•
•
Course Overview
Internet Architecture
Introduction to JavaScript
Demo
2
Course Overview
• Course outline
https://scs.senecac.on.ca/course/int222
• Course standards
http://wsong18.wordpress.com/standards/
• Academic Honesty Policy
https://scs.senecac.on.ca/page/academic-honesty-policy
• In this course, you will learn web client (frontend) development concepts and techniques,
using JavaScript, HTML and the DOM, and CSS.
3
Evaluation
6 labs
(1 % or 2% each)
10%
3 quizzes (1.5% or 2% each )
5%
3 assignments (6% + 6% + 8%=) 20%
2 term tests (17% + 18%=)
35%
Final exam
30%
---------------------------------------------------Total
100%
4
Promotion Policy
To obtain a credit in this subject, a student must:
• Achieve a grade of 50% or better on the final
exam
• Satisfactorily complete all assignments
• Achieve a weighted average of 50% or better
for the tests and final exam
• Achieve a grade of 50% or better on the
overall course
5
Communication
• Blackboard
• My web site:
http://wsong18.wordpress.com/
• INT222 course site
https://zenit.senecac.on.ca/~emile.ohan/int222/weekly.html
• Email:
wei.song@senecacollege.ca
• Student help hours:
http://zenit.senecac.on.ca/~wei.song/
• Office room: Tel -2101
6
Coordinate with other sections
•
•
•
•
•
•
Common assignments
Common labs (but different due dates)
Common final exams
Similar term tests
Similar quizzes?
Matched lectures
– Lecture Slides on my web page
– Weekly Notes on INT222 site
7
Expectation
• Mine:
– Be present. Practice.
– Learning strategy:
• Getting the big picture (concepts, framework,
architecture)
• paying attention to the details (coding, syntax, handson)
• Memorizing something!
• Yours?
8
Introduce to Internet architecture
About the Internet architecture
• The Internet’s architecture is described in its name, a
short form of the compound word “inter-networking”.
• This architecture is based in the very specification of
the standard TCP/IP protocol, designed to connect any
two networks which may be very different in internal
hardware, software, and technical design.
• Once two networks are interconnected,
communication with TCP/IP is enabled end-to-end, so
that any node on the Internet has the near magical
ability to communicate with any other no matter
where they are. This openness of design has enabled
the Internet architecture to grow to a global scale.
10
The Internet map : router-based
interconnectivity
11
The Internet Reference Model and the
protocol stack
• We may mainly deal with application (layer) protocols.
12
Internet application protocols
• Remote login category
– Telnet
– SSH, Secure Shell
• File transfer category
– FTP, File Transfer Protocol
– TFTP, Trivial File Transfer
Protocol
• Electronic mail category
– SMTP, Simple Mail Transfer Protocol
– IMAP, Internet Message Access
Protocol
– POP, Post Office Protocol
• Other protocols
─ HTTP, HyperText Transfer Protocol
• Support services category
─ HL7, Health Level Seven
– DNS, Domain Name System
─ LDAP, Lightweight Directory Access
– SNMP, Simple Network
Protocol
Management Protocol
─ NFS, Network File System
– CMOT, Common Management ─ DHCP, Dynamic Host Configuration
Information Protocol
Protocol
─ IRC, Internet Relay Chat
─ …
13
A port number is reserved for each
the services on a server
• FTP (file transfer protocol) - usually on port 21
• SFTP (Secure file transfer protocol) - usually on
port 22
• SSH (Secure Shell) - used for secure logins usually on port 22
• telnet - usually on port 23
• http - usually on port 80
14
Services provided by the Internet
• World Wide Web (the Web )
– It is a collection of web pages connected through hyperlinks and URLs.
– It is governed by the Hyper Text Transfer Protocol (HTTP) that deals
with the linking of files, documents and other resources of the web.
•
•
•
•
•
•
•
Electronic Mail (email)
Mailing List
File Transfer Protocol (FTP)
Instant Messaging
News Groups
Chat Rooms
Chat
15
HyperText Transfer Protocol
What is HTTP
• HTTP, the Hypertext Transfer Protocol, is the applicationlayer protocol that is used to transfer data on the (World
Wide ) Web.
• HTTP comprises the rules governing the format and content
of the conversation between a web client and server.
• HTTP functions as a request-response protocol in the clientserver computing model.
– It follows a classical client-server model, with a client opening a
connection, making a request then waiting for a response until it
receives it.
• HTTP is stateless.
– The server doesn't keep any data (state) between two requests.
• Latest version is HTTP 1.1
17
HTTP transaction
18
HTTP Request and response messages
19
Structure of the HTTP request
• A HTTP (client) request consists of text directives,
divided in three blocks:
1. The first/request line contains a request method, the
HTTP protocol version used, followed by the path of
the document.
2. The subsequent block represents specific request
headers
• Gives the server some information about what kind of data is
appropriate (e.g., what language, what MIME types) or some
data altering its behavior (e.g., not sending an answer if it is
already cached).
• This block ends with an empty line.
3. The final block is the optional data block/request
body.
• Contains further data and is mainly used by the POST
method.
20
An example of HTTP requests
• Fetching the root page of developer.mozilla.org,
i.e. http://developer.mozilla.org/, and telling
the server that the user-agent would prefer
the page in French, if possible:
GET / HTTP/1.1
Host: developer.mozilla.org
Accept-Language: fr
21
Another example
• Sending the result of a form:
POST /contact_form.php HTTP/1.1
Host: developer.mozilla.org
Content-Length: 64
Content-Type: application/x-www-form-urlencoded
name=Joe%20User&request=Send%20me%20one%20of%2
0your%20catalogue
22
HTTP request methods
23
Structure of a server response
• Similarly to a client request, a server response
is formed of text directives, divided in three
different blocks:
1. The first block, the status line, consists of an
acknowledgment of the HTTP version used,
followed by a response status codes.
2. The subsequent block contains response headers,
giving the client some information about the data
sent and ends with an empty line.
3. The final block is the data block/response body,
which contains the data (if any).
24
An example of server responses
• Successful reception of a web page:
HTTP/1.1 200 OK
Date: Sat, 09 Oct 2010 14:28:02 GMT
Server: Apache
Last-Modified: Tue, 01 Dec 2009 20:18:22 GMT
ETag: "51142bc1-7449-479b075b2891b"
Accept-Ranges: bytes
Content-Length: 29769
Content-Type: text/html
<!DOCTYPE html... (here comes the 29769 bytes of the
requested web page)
25
Another example
• A server notification that the requested resource
doesn't exist:
HTTP/1.1 404 Not Found
Date: Sat, 09 Oct 2010 14:33:02 GMT
Server: Apache
Last-Modified: Tue, 01 May 2007 14:24:39 GMT
ETag: "499fd34e-29ec42f695ca96761;48fe7523cfcc1"
Accept-Ranges: bytes
Content-Length: 10732
Content-Type: text/html
<!DOCTYPE html... (contains a site-customized page
helping the user to find the missing resource)
26
HTTP response status codes
27
HTTP header fields
28
HTTP Secure
• Hypertext Transfer Protocol Secure (HTTPS) is
a communications protocol for secure
communication over a computer network, with
especially wide deployment on the Internet.
• Technically, it is not a protocol in and of itself;
rather, it is the result of simply layering the
Hypertext Transfer Protocol (HTTP) on top of
the SSL(Secure Sockets Layer)/TLS(Transport Layer
Security) protocol, thus adding the security
capabilities of SSL/TLS to standard HTTP
communications.
29
Web Technology
Web Technology Basic
• The World Wide Web is a system of interlinked hypertext
documents accessed via the Internet. The two basic components of
the Web are the Web browser client and the Web server.
• Three fundamental elements comprise the technology architecture
of the Web:
– Uniform Resource Locators (URL)
• A standard syntax used for creating identifiers that point to Web-based
resources.
• eg. https://zenit.senecac.on.ca/~int222_141a45/index.html
– protocol = https://
– domain name = zenit.senecac.on.ca
– path or URI - uniform resource indicator = ~int222_141a45/index.html
– Hypertext Transfer Protocol (HTTP)
• This is the primary communications protocol used to exchange content and
data throughout the World Wide Web. URLs are typically transmitted via HTTP.
– Markup Languages (HTML, XML)
• Markup languages provide a lightweight means of expressing Web-centric data
and metadata. The two primary markup languages are HTML (which is used to
express the presentation of Web pages) and XML (which allows for the
definition of vocabularies used to associate meaning to Web-based data via
metadata).
31
Web Applications
• A distributed application that uses Web-based
technologies (and generally relies on Web
browsers for the presentation of userinterfaces) is typically considered a Web
application.
• These applications can be found in all kinds of
cloud-based environments due to their high
accessibility.
32
The common architectural abstraction
for Web applications
• It is based on the basic threetier model.
– The first tier is called
the presentation layer, which
represents the user-interface.
• The presentation layer has
components on both the client and
server-side.
– The middle tier is the application
layer that implements
application logic.
– The third tier is the data
layer that is comprised of
persistent data stores.
33
Front-end web application
• The rising popularity of so-called “modern”
web apps means that web developers are
focusing on writing more and more front-end,
or client-side code. Although back-end, or
server-side code still plays an important factor,
the fact is that web developers are working
more directly with HTML5, CSS3, and
JavaScript.
34
The architecture for front-end web
application
• What is the front-end/clientside doing?
–
–
–
–
Render UI
Interactivity
Logical requests to server
UI state management
• What is the server-side doing?
– Authority on request integrity
– Accessing/updating DB
– Serving data
35
Web Development
• is hard.
• You must know at least 3 (often 4) programming
languages:
– JavaScript
• the state and behavior of the frontend
– CSS
• how things look
– HTML
• structure of the UI/Document
– Server Programming (INT322)
• Stateful storage and interaction with other servers
36
Introduction to JavaScript
What is a Script
• A script is a high-level programming language that is
interpreted by another program at runtime rather than
compiled by the computer's processor (as other
programming languages such as C and C++ are).
• Some types of languages are client-side scripting
languages, affecting the data that the end user sees in
a browser window. Other scripting languages are
server-side scripting languages that manipulate the
data, usually in a database, on the server.
• Scripting languages came about largely because of the
development of the Internet as a communications tool.
JavaScript, ASP, JSP, PHP, Perl, Tcl and Python are
examples of scripting languages.
38
What is JavaScript?
• JavaScript (JS) is a cross-platform Web scripting
language.
– JavaScript always runs inside a host environment
(mostly the browser).
• JavaScript is a prototype-based scripting language
with dynamic typing and has first-class functions.
– There is no class in JS (constructors do what classes
do).
– The object-based language with prototyping: powerful
prototypal object-oriented language
– In JavaScript every function is actually a Function
object.
39
About JavaScript
• JavaScript is one of the world's most popular
programming languages .
– The role as the scripting language of the WWW.
– simple and easy to learn
• JavaScript is the world's most misunderstood
programming language.
– The name, typecasting, used by amateurs, objectoriented,…
• JavaScript is, in the future, the most important
language you will learn(? Dart?)
40
JavaScript History
• JavaScript was developed in 1995 by Brendan Eich at
Netscape, now a division of America Online.
• JavaScript started with simple one-liners embedded in
HTML.
• The JavaScript backlash (incompatibility, …) caused some
web projects to completely ban any client-side
programming and trust only their predictable and reliable
server.
• ECMAScript (European Computer Manufacturers
Association) was born, making healthier environment.
• JavaScript is now used in much more sophisticated ways.
– Developers leverage the object-oriented nature of the language
to build scalable code architectures made up of reusable pieces.
– JavaScript provides behavior, the third pillar in today's paradigm
• web pages consist of three clearly distinguishable parts: content
(HTML), presentation (CSS), and behavior (JavaScript).
41
The Present
• Today, you can use JavaScript to do all of this:
– Create rich and powerful web applications (the kind of
applications that run inside the web browser, such as Gmail)
– Write server-side code such as ASP scripts or, for example,
code that is run using Rhino (a JavaScript engine written in
Java)
– Create rich media applications (Flash, Flex) using
ActionScript, which is based on ECMAScript
– Write scripts that automate administrative tasks on your
Windows desktop, using Windows Scripting Host
– Write extensions/plugins for a plethora of desktop
application such as Firefox, Dreamweaver, and Fiddler
– Create web applications that store information in an off-line
database on the user's desktop, using Google Gears
– Create Yahoo! Widgets, Mac Dashboard widgets, or Adobe
Air applications that run on your desktop
42
Front-end Apps Demo
The Planetarium
Beautiful Web Introduction to the solar system
BananBread
Web FPS shoorter
CSS Tricks
Web Animation (using data from 3d body tracking)
43
Let’s start with JavaScript
Firefox Scratchpad
• Why use Scratchpad?
– JavaScript always runs inside a host environment (mostly
the browser).
• To use Scratchpad, go to the “Web Developer” menu
(hint for Mac users: look for the “Web Developer”
menu under “Tools”). Select “Scratchpad” from that
menu, and you’ll get a text editor window.
• Shortcut: Shift+F4
• How to run a script:
1. Enter some code
2. Select a portion of the code
3. Choose one of the three commands from the Execute
45
prompt()
• This built-in function (of the Window object)
will display a dialog box (Modal window) that
prompts the visitor for input.
• Gets user input. Rarely used.
• Example code:
var ok = prompt("Are you OK?");
alert(ok);
1+2; // Instpct/display executes the selected code,
//and the result is put right into your editor.
46
alert()
• Pops up an alert box (Modal window) with a
message and an OK button.
• Outputs info.
• Example code:
function sayHello() {
alert("Hello from the Scratchpad");
}
sayHello();
alert("This is alert 2");
alert(42);
47
console.log()
• Shows a message in web console.
• Outputs info.
• Example code:
var someObject = { str: "Some text", id: 5 };
console.log(someObject);
• View log:
– Ctrl + Shift + J to open browser console.
48
Create/edit/save the source code
• Although web client programming allows us to
place JavaScript inline or internal to a
document , we prefer that you store your
JavaScript code in its own source code file.
• You can use any text editor, Scratchpad or
programmer’s editor.
• We suggest that you store your code in the
xxx/js folder, and name each source code file
by using a .js extension.
49
LET’S TAKE A LOOK AT SOME
SYNTAX
50
JavaScript is a C-family/style language
• A rich set of operators are available, using a
comfortable C-like syntax.
• Statements should end with a ; semicolon, just
like in C.
• Expressions are also similar to C, and you can use
operators on objects without conversions.
• Curly braces { } are used as code block delimiters.
Scoping follows rules similar to C (but are
different, as you will learn).
• Similar to C, if-else (including the ? : syntax) and
switch-case are available in JS.
• for and while are available in JS.
51
Comments and more
• JavaScript supports two kinds of comments:
– A block comment starting with /* and ending with
*/ that may span several lines.
• (This is the same form as a CSS comment.)
– A line comment that starts with // and goes to the
end of the line.
• JavaScript is case-sensitive
52
Declare and Refer Variables
• You must use the “var” keyword to precede a
variable name.
• Unlike the C language, you do not need a type
specifier.
– The variable’s initial value will set its initial type.
• Declaration syntax:
var variableName;
var variableName = value;
// Referring to and using syntax:
variableName = someValue;
document.write(variableName);
53
Arithmetic Operators
Operat
or
Operation
Example
+
addition of numbers
Concatenation of
strings
y + x;
“INT” + “222”
-
subtraction
x - y;
*
multiplication
x * y;
/
division
x / y;
%
modulo
x % y; // remainder of x divided by y
++
post/pre -increment
x = y++; // assign y to x, then increment y (y+=1)
x = ++y; //increment y < (y+=1), then assign y to x
--
post/pre decrement
x = y--; // assign y to x, then decrement y (y-=1)
x = --y; // decrement y < (y-=1), then assign y to x
54
Assigning Values
Operator
Example
Equivalent
For
=
a = b;
a = b;
numbers or strings
+=
a += b;
a = ( a + b);
numbers or strings
-=
a -= b;
a = ( a - b);
numbers
*=
a *= b;
a = ( a * b);
numbers
/=
a /= b;
a = ( a / b);
numbers
%=
a %= b;
a = ( a % b); // divide a by b,
// assign remainder to a
numbers
55
Logical Operators
Operator
Operation
&&
Logical AND
||
Logical OR
!
Logical NOT
Example
expr1 && expr2
expr1 || expr2
!expr1
56
Other Operators
• Conditional Operator:
Result = (condition)?"if true":"if false";
e.g. var Grade=(mark<50)?"Fail":"Pass";
• The typeof operator (for variable or values):
– possible return values:
"undefined“, "object“, "boolean“, "number“, "string“,
"function“, "xml“, "object“
• The instanceof operator
–…
57
Comparison Operators
Operator
Description
Example
==
Equal
(The operands are converted to the
same type before being compared.)
1 == 1 is true
1 == "1" is true
1 == true is true
0 == false is true
===
strictly equal
(There is no type conversion.)
1 === 1 is true
1 === "1" is false
1 === true is false
0 === false is false
!=
not equal
(with type conversion)
1 != 1 is false
1 != ‘1’ is false
!==
not equal
(without type conversion)
1 !== 1 is false
1 !== ‘1’ is true
>
greater than
expr1 > expr2
>=
greater than or equal to
expr1 >= expr2
<
less than
expr1 < expr2
<=
less than or equal to
expr1 <= expr2
58
Strings and Quotation Marks
• Literal strings can be denoted by either single
or double quotes, which gives you some
flexibility about how to handle awkward
situations such as quotation marks inside a
string:
Expression
Values
"Let’s start with JavaScript”
Let’s start with JavaScript
'Not "it"!'
Not "it"!
59
Concatenation of Strings
• The main operation on strings is the
concatenation operator, +:
Expression
Value
“INT" + “222"
INT222
“Stephen” + “ Harper”
Stephen Harper
60
The prompt() Function
• Examples:
var a = prompt("Enter first number"); // enter 11
var b = prompt("Enter second number"); // enter 12
var result = a + b;
alert("The result is " + result); // What is the result?
• Default values
var school = prompt("What is your school?", “Seneca");
alert("Oh, you go to "+school+". How nice.");
• Warning: The prompt() function does not work properly
in certain browsers. So it's best not to use it in projects.
61
The parseInt() and parseFloat()
• Used to convert from a string of digits to
numbers.
Expression
Value
parseInt("243",10)
243
parseInt("cs110",10)
NaN (Not a Number)
parseFloat("3.141")
3.141
parseInt("3.141",10)
3
• The second argument to parseInt() is the radix
or base that you want to use.
62
Lab Practices
• Lab on the INT222 Site:
– Updating your index.html
– Due on:
• Section D: Jan 11, 2014
• Section C: Jan 16, 2014
• Practice Scratchpad
63
Week 1 reading reference
• HTTP (MDN): https://developer.mozilla.org/enUS/docs/HTTP
• Firefox Developer Tool – Scracthpad (MDN):
https://developer.mozilla.org/en-US/docs/Tools/Scratchpad
• (Core) JavaScript Guide (MDN):
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
• JavaScript Syntax Reference:
https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Statements
64
• The matched content for this slides can also
be found on the INT222 Course Site Weekly
Notes:
1. Week 01 - January 6, 2014
2. Week 02 - January 13, 2014
Thank You !
65
Download