• No results found

IA 07 internet apps js intro pdf

N/A
N/A
Protected

Academic year: 2020

Share "IA 07 internet apps js intro pdf"

Copied!
31
0
0

Loading.... (view fulltext now)

Full text

(1)

ASP.NET and derivatives

HTML5 =

Markup + CSS +

JavaScript APIs

JavaScript intro

(2)

Client vs. Server

• HTML is just a markup language and when combined with CSS capable of producing just about every design you could ever desire • In order to have dynamic web content one need to do some client

side programming to produce a RIA (Rich Internet Application)

• Client-based programming means that programs run on the visitor’s computer, within their web browser

– All web browsers support this via JavaScript

– Adobe ActionScript is another common technology (Adobe Flash) which is similar to JavaScript

• Server-side programming means that programs run on the web server. The browser never gets to see the program code, only the resulting HTML

– Most common languages for writing server-side programs are PHP, Perl, Python, Ruby and Java, as well as Microsoft’s proprietary

languages ASP, ASP.NET and ASP.NET Web Forms/MWC/Web Pages • Which one of these paradigms to use?

(3)

ASP.NET Web Forms vs.

ASP.NET MVC similarities, both:

• is built on top of the ASP.NET framework

i.e. The System.Web namespace

Leverage .NET framework and its languages

• use IIS and the ASP.NET request pipeline

HTTP handlers, HTTP modules and other

components as the configuration framework etc.

Adobe ActionScript is another common technology

(Adobe Flash) which is similar to JavaScript

• render a response to the user

(4)

ASP.NET Web Forms vs.

ASP.NET MVC differences

ASP.NET Web Pages with Razor syntax provide a fast and lightweight way to combine server code with HTML to create dynamic web content using the latest web standards.

(5)

Razor and TypeScript

• Razor syntax, three basic rules

• Just write code and markup – don't think about it

• @ indicates code

• Standard language keywords

e.g. if/else, foreach, etc.

• TypeScript is an Open Source language for

application-scale JavaScript development that

compiles to plain JavaScript

http://www.typescriptlang.org/

else{

<span>@auction.CurrentPrice.Value.ToString("C")</span> }

(6)

JavaScript

• JavaScript was originally developed by Brendan Eich of Netscape around 1995, currently Mozilla Foundation

• JavaScript is formalized in the ECMAScript language standard

• JavaScript uses syntax influenced by C and copies many names and naming conventions from Java - NOT to be confused with the Java programming language!

• JavaScript is mainly used in browsers but also in applications outside Web pages as

– PDF documents and desktop widgets, runtimes as node.js etc. • Major implementations

– KJS, Rhino, SpiderMonkey, V8, WebKit, Carakan, Chakra • JavaScript uses dynamic typing as most scripting languages do

– For example, a variable x could be bound to a number, then later rebound to a string

(7)

What can a JavaScript (JS) do?

• JS is a scripting language with a very simple syntax

– Almost anyone can put small "snippets" of code into their HTML pages

• JS can be set to execute when something happens, like when

a page has finished loading or when a user clicks on an HTML

element

• JS can be used to validate form data before it is submitted to a

server

– This saves the server from extra processing

• JS can be used to detect the visitor's browser, and load

another page specifically designed for that browser

• JS can be used to store and retrieve information on the

visitor's computer

• JS can read and change the content of an HTML element

JS uses the HTML DOM (Document Object Model) to

(8)

What is the HTML DOM?

• The HTML DOM (Document Object Model) defines a standard way for accessing and manipulating HTML documents

• One of the most common uses for JavaScript is for navigation and drop-down menus etc. making it look like desktop applications

• The DOM presents a HTML document as a tree-structure

(9)
(10)

How

does

HTML

5

(11)

JavaScript locations

• JavaScript can be written

in the following places

• <body>

The script generate

content

when the page

is loaded

• <head>

The script generate

content when

it is

needed

or

before the

page loads

We write our functions

here

(12)

Simple JavaScript

• An alert will pop up and we write the current time in the document • Since the JS code is visible via view source in the browser NEVER

do anything regarding security or authentication in JavaScript!

<!doctype html> <html>

<head>

<meta charset="utf-8"> <title>Hello Time</title>

<script>

// runs before page load

alert("Hello World!");

</script>

</head>

<body>

The current time is:

<script>

var d = new Date();

if (d.getHours() < 10) {

document.write("0");

}

document.write(d.getHours());

document.write(".");

if (d.getMinutes() < 10) {

document.write("0");

}

document.write(d.getMinutes());

document.write(".");

if (d.getSeconds() < 10) {

document.write("0");

}

document.write(d.getSeconds());

</script> </body> </html>

co

nt

.

(13)

JavaScript, DHTML and AJAX

• In HTML5 JavaScript is the standard script language

• JavaScript is object oriented and can be used with AJAX

(Asynchronous JavaScript and XML) and JSON

(JavaScript Object Notation) technologies

– JSON is a text-based standard for data exchange (as XML)

• The connection between HTML5 (or XHTML),

stylesheets and JavaScript is very strong

• DHTML (Dynamic HTML) = manipulation of the DOM

• AJAX = DHTML + XMLHttpRequest object

AJAX makes it possible to update parts of the web page

from a server via some AJAX script (JavaScript) without

reloading the whole web page

(14)

JavaScript testing/debugging

• We preferably write JavaScript in some kind of text-editor

which highligts the syntax as Notepad++ etc.

– CodeLobster have help and intellisense support!

• To debug (stepwise execution and variable inspection) our

JS code we use the built-in web browsers facilities

– Internet Explorer and Edge – F12

– Google Chrome, Mozilla Firefox – Ctrl-Shift-I

– Add-ons/Extensions – Web developer toolbox, Firebug plugin, etc.

• With debug ON you can examine almost everything in JS!

(15)

JavaScript rules

• In JavaScript, each line of code is considered to end either at

the

end of the line

or

at the semicolon

– Best practice is to always end every call with a semicolon!

• Both single

'

and double

quotes can be used to mark

strings - as long as the quotes at the start and the end of the

string match

• JavaScript code/syntax is case sensitive

• Comments in JavaScript is done as in C/C++ or Java/C#

• It is best to test JavaScript on a web server since some

browsers may not work correctly if the web page is local

– This is related to security concerns

• Actually it *is* impossible for JavaScript to access local files

on a computer using < HTML5 with one exception – cookies

(16)

The window object and variables

• The window object is the highest object in the DOM

hierarchy (above document in earlier DOM slide)

You do not need to include it when writing your code

window.document.write(”text”); => document.write(”text”);

• Variables usually have a

datatype

, name and a

value

var

var_name

=

var_value

;

• Variable rules

Must begin with a letter or underscore (digits may be used

after first character)

Variables names are case sensitive

JavaScript does

not warn

for variables with same name!!

Variable should have describing names of several reasons

• There are no datatypes in JavaScript

(17)

Aritmetic operators

• Javascript use dynamic typing - the JavaScript interpreter

will figure out what type to use as your code is running

• Operations and operators are more or less exactly as in

C# or Java

Mathematical as (+, -, *, /, %), + also concatenate strings

– var str = ”my ” + ”name”;

Stepwise increment/decrement (++/--)

– a = a+1; (a += 1)

Compare and relation

– (==, !=), (>, >=, <, <=)

– (===, !==) when NOT automatic type conversion will be done

Logic operations

(18)

Variable and function

//Variable is a symbolic name for a value.

//Variables are declared with the var keyword:

var x; // Declare a variable named x.

//Values can be assigned to variables with an = sign

x = 0; // Now the variable x has the value 0

x // => 0: A variable evaluates to its value.

//JavaScript supports several types of values

x = 1; // Numbers.

x = 0.01; // Just one Number type for integers and reals.

x = "hello world"; // Strings of text in quotation marks.

x = 'JavaScript'; // Single quote marks also delimit strings.

x = true; // Boolean values.

x = false; // The other Boolean value.

x = null; // Null is a special value that means "no value".

x = undefined; // Undefined is like null.

//A function is a named and parametrized block of JavaScript code //that you define once, and can then be invoked over and over again.

function plus1(x) { // Define a function named "plus1" with parameter "x"

return x+1; // Return a value one larger than the value passed in

} // Functions are enclosed in curly braces

plus1(y); // => 4: y is 3, so this invocation returns 3+1

var square = function(x) { // Functions are values and can be assigned to vars

return x*x; // Compute the function's value

}; // Semicolon marks the end of the assignment.

(19)

Dialogs

• The

alert

dialog

– Inform the user – general information, warnings etc.

– For development showing variables

• The

prompt

dialog

– Lets the user enter text which can be returned to a variable

– var passwd = window.promt('...');

• The

confirm

dialog

– Returns true or false

– var cont = window.confirm('…');

<script>

window.alert("Information...");

var passwd = prompt("Enter password"); var cont = confirm("Continue?");

(20)

while, for, if, else

<!doctype html>

<html> <head>

<meta charset="utf-8">

<title>My First JavaScript</title> </head>

<body> <script>

var drink = "beer";

var lyrics = "";

var cans = 5;

for(cans=5; cans > 0; cans--) /*while (cans > 0)*/ {

lyrics = lyrics + cans + " cans of "

+ drink + " on the wall <br>"; //End the line with a HTML line break. lyrics = lyrics + cans + " cans of " //Do it again

+ drink + "<br>";

//Add the next verse, again using concatentation.

lyrics += "Take one down, pass it around,<br>"; // using += operator

if (cans > 1) {

lyrics += (cans-1) + " cans of " //... add the last line. + drink + " on the wall <br>";

}

else { //otherwise, there are no cans left...

lyrics = lyrics + "No more cans of " //add “No more cans” to the end of lyrics. + drink + " on the wall <br>";

}

(21)

<noscript> element

• Check if the user have JavaScript enabled in his browser

– The <noscript> element can contain all the elements that you can find inside the <body> element of a normal HTML page

– The content inside the <noscript> element will only be displayed if scripts not are supported, or are disabled in the user’s

browser

Getting the screen size

<!doctype html> <html><head>

<meta charset="utf-8"> <title>Screen Size</title> </head><body>

<noscript>Your browser does not support JavaScript!</noscript>

<script language="javascript">

var w = window.screen.availWidth; var h = window.screen.availHeight;

document.write("Your browser support JavaScript! W: " + w + ", H: " + h); if ((w <= 1024) && (h <= 768))

document.write("<img src=image1.jpg>"); else if ((w > 1024) && (h > 768))

document.write("<img src=image2.png>"); </script>

</body></html>

screensize.html

(22)

Variable problems

• Since the var type handles any datatype problems can occur

• If you use a ”variable” that has not been declared with the reserved keyword ”var” a runtime error oc

cur

• Use strict mode to introduce better error-checking of your code

– Since 2013 Chrome, Firefox, IE and Edge support ”strict mode”

– http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/ • If you use a non initialized variable

it will have the value undefined or NaN

<script>

"use strict";

num; // error!

num = 3; // ok, but avoid! var num0;

var num1 = 3; var num2 = 3.14;

var passwd = "qwerty"; var cont = true;

</script>

<script>

var myVar;

function foo1(){

return myVar - 2; }

function foo2(){

return myVar + "text"; }

function foo3(){

return !myVar; }

foo1(); // returns NaN

foo2(); // returns undefined

foo3(); // returns true

</script>

(23)

Variable scope – strict support

• Any variable created without the

var

keyword is created at the

global scope and is not garbage collected when the function

returns (because it doesn’t go out of scope), giving the

opportunity for a memory leak!

<script>

/* Difference between using var and not using var in JavaScript?

If you're in the global scope then there's no difference. If you're in a function then "var" will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it) */

// These are both globals

var foo = 1; bar = 2;

function scope(){

var foo = 1; // Local

bar = 3; // Global

return (function(){ "use strict"; return !this; })(); //a nameless function

}

// If you're not doing an assignment then you need to use var:

// var x; // Declare x document.write(scope()); </script>

scope.html

(24)
(25)

Reserved words ...

• In addition to the reserved words, you'd better avoid the

following identifiers as names of JavaScript variables

– These are predefined names of implementation-dependent JavaScript objects, methods, or properties (and, arguably, some should have been reserved words)

• Examples

Alert, Array, close, radio and so on, around 100 words!

• Similarly, the following names (depending on your target

browser) may have special meanings as

event handlers,

and therefore should not be used for any other purpose

• Examples

onclick, onload, onmouseover and so on...

Around 20 in HTML4, HTML5 adds around 50 more

(26)

Global functions - isNaN(), parseInt()

• isNaN(number : Number) : Boolean

– Check if the parameter is NaN (Not a Number)

– Reterns true if number is NaN otherwise false (it is a number)

– Useful when checking user entered data in forms

• parseInt(numString : String [, radix : Number]) : Number

– Converts a string into a number with the base radix

– Returns the first valid number it finds

– If no number is found NaN is returned

alert("isNaN(43): " + isNaN("43"));

parseInt("abc") // Returns NaN parseInt("12abc") // Returns 12

(27)

Global functions - parseFloat(), isFinite()

• parseFloat(numString : String) : Number

– Returns a floating-point number converted from a string

– Reterns true if numString is NaN otherwise false (it is a number)

– You can test for NaN using the isNaN method

• isFinite(number : Number) : Boolean

– Returns a Boolean value that indicates if a supplied number is finite – you cannot do division with 0

– The isFinite method returns true if number is any value other than NaN, negative infinity, or positive infinity. In those three cases, it returns false

alert("isFinite(10/0): " + isFinite(10/0));

parseFloat("abc") // Returns NaN.

ParseFloat("1.2abc") // Returns 1.2

(28)

<!doctype html> <html lang="en">

<head>

<meta charset="utf-8">

<title>Movies</title>

</head>

<body>

<h1>Movie Showtimes</h1>

<h2 id="movie1" >Plan 9 from Outer Space</h2>

<p>Playing at 3:00pm, 7:00pm. <span>

Special showing tonight at <em>midnight</em>! </span>

</p>

<h2 id="movie2">Forbidden Planet</h2>

<p>Playing at 5:00pm, 9:00pm.</p>

</body> </html>

JS and the DOM

• Do you still remember the

DOM (Document Object

Model)?

• Lets say we have the

following web page →

(29)

document.getElementById()

• oElement = object.getElementById(sIDValue)

– Returns a reference to the first object with the specified value of the ID attribute

– sIDValue is a String that specifies the ID value, case-insensitive.

• If we would like to update the text on one of the movies we could use innerHTML - it will be updated after the page has loaded

• Remeber: You cannot modify the DOM before the page has loaded!

• Other things that can be done is

– Add and remove elements to/from the DOM

– Get and set other element attributes than text <script>

function init() {

var title = document.getElementById("movie1");

title.innerHTML = "Red planet";

}

// when the page have fully loaded execute init, note that // we do not specify init() since it would run at once then window.onload = init;

</script>

(30)

Event functions or methods

<script>

"using strict"; function myFunc1() {

var text =

document.getElementById('txt').value; console.log(text);

alert(text); }

function myFunc2(text) { console.log(text); alert(text);

}

</script> </head> <body>

<label>Name</label> <input id="txt" name="name" type="text"

size="20" value="text" onmouseover="myFunc1();" /> <br /> <br />

<input type="button" value="choose" onclick="myFunc2('input button');" />

<br /> <br />

<button ondblclick="console.log(alert('button'));">No</button>

</body>

myeventfunc.html

• The JavaScript functions are sometimes called methods

• Functions can be called from global events which fire off

according to the HTML standard event attributes

• With document.getElementById(<element sId>)

.value

(31)

Debug with console.log()

• You can use the function console.log() to display text in the JS

console which is less intrusive than alert() or document.write()

myeventfunc.html

console.log()

References

Related documents

There are certainly many traditional approaches to reduce radar noises like matched filter, but this paper will present a novel approach of noise removal via sensor fusion

El objetivo del trabajo fue conocer las especies de Syrphidae (Insecta: Diptera) presentes en el Parque Universitario de la Universidad Centroccidental

Topics include design of a web site and web pages, Hypertext Markup Language (HTML), style sheets, scripting languages, dynamic web pages, database connectivity, web servers,

women who are long-term survivors of breast cancer and this study aims to report the stories of African American women who are disease-free survivors, 10 or more years after

The understanding of what constitutes a ‘‘good’’ production schedule is central to the development and evaluation of automated scheduling systems and their implementation

Aspiration of foreign bodies results in the death of more than 500 children per year in the United States.1 Foreign body aspiration may be manifested by acute

• Create user services including Web server controls, HTML server controls, user controls and HTML code for ASP.NET pages.. • Create and manage components and .NET assemblies •