dad 06.2 javascript arreglos objetos

Post on 22-Oct-2014

82 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Desarrollo de Desarrollo de aplicaciones distribuidasaplicaciones distribuidas

6.2 Programación cliente-Servidor.

JavaScript (Arreglos y objetos).

Dr. Alejandro Rosete SuárezDr. Alejandro Rosete Suárez

Alejandro.rosete.suarez@itesm.mx

Alejandro.rosete.suarez@gmail.com

rosete@ceis.cujae.edu.cu

DAD (98) 2

– Características de los sistemas distribuidos – Modelos de capas – Modelos de distribución– TCP/IP, HTTP, FTP – Bases de datos en sistemas distribuidos – Creación y reutilización– Generación de contenidos dinámicos

Tema 2: Paradigmas de software distribuido. Programación en cliente.

DAD (98) 3

Estándares NavegadoresProgramación en el cliente con Javascript. Otras tecnologías. DOM, JSF, AJAX.

Tema 2: Paradigmas de software distribuido. Programación en cliente.

DAD (98) 4

Deitel, Harvey M.-, Internet and the World Wide Web : how to program / H.M. Deitel, P.J. Deitel, T.R. Nieto., , Upper Saddle River, N.J. : Prentice Hall 2008

– Cáp. 21 (Paradigmas distribuidos)– Cap. 10, 11, 12 y 13. JavaScript

Arreglos. Objetos Eventos DOM

Libro de texto

DAD (98) 5

Contenido de HOY

Paradigmas de software distribuido.JavaScript

– Arreglos

– Objetos

– Separación y reutilización de programas

DAD (98) 6

Deitel, Harvey M.-, Internet and the World Wide Web : how to program / H.M. Deitel, P.J. Deitel, T.R. Nieto., , Upper Saddle River, N.J. : Prentice Hall 2008

– Cáp. 10 y 11. JavaScript Arreglos Objetos

Repasar lo visto en Parcial 1.

Libro de texto

DAD (98) 7

Internet

DAD (98) 8

Internet = Interconnected Networks 1969: La primera célula de la actual

Internet se creó con ARPAnet. 1970: Se interconectaron las principales

universidades y centros de investigación científica de EE.UU.

1983: ARPANET se separa de la red militar que la originó. (MILNET) y (ARPAnet)

DAD (98) 9

1989: ARPANET desapareció oficialmente.

Mediados de los ‘90: Se forma la red

comercial e informativa que es en la

actualidad Internet.

1995: Entre 35 y 45 millones de personas

utilizaban Internet. Crecimiento mensual del

10 al 15%.

DAD (98) 10

Para llegar a 50 millones de usuarios:–Telefonía fija: 74 años–Radio: 38 años–Computación: 16 años–Televisión: 13 años

Internet: 4 años

DAD (98) 1111

usuarios de Internet 360,985,492 diciembre de 2000

1,463,632,361 Junio de 2008

1,668,870,408 junio de 2009

Tomado de: http://www.internetworldstats.com/stats.htm

0

500,000,000

1,000,000,000

1,500,000,000

2,000,000,000

2000 2002 2004 2006 2008 2010

DAD (98) 1212

Internet Web

Computadoras Documentos, sonidos, videos... información

Cables entre computadoras

Enlaces entre hipertextos

Las web no existiría sin InternetInternet no sería tan popular sin la

Web

DAD (98) 13

Una de las diferencias entre Internet con los demás medios de comunicación Interacción y personalización de

la información con el usuario. Sin embargo, HTML es estático. Surgimiento de tecnologías

interactivas Del lado del cliente. Del lado del servidor.

DAD (98) 14

DAD (98) 1515

Clasificación de Sistemas Computacionales

desde el punto de vista de la distribución

DAD (98) 1616

A distributed network architecture may be called a Peer-to-Peer (P-to-P, P2P,…) network, if the participants share a part of their own hardware resources (processing power, storage capacity, network link capacity, printers,…). They are accessible by other peers directly, without passing intermediary entities. The participants of such a network are thus resource (Service and content) providers as well as resource (Service and content) requestors […].”

DAD (98) 1717

The most commonly used paradigm in constructing distributed systems is the Client-Server model. In this scheme clients request services or content from a server.

The client and server require a known set of conventions before the can communicate (protocol).

DAD (98) 18

ServidorCliente

Hace una solicitud

Responde la solicitud

Navegador webEj.: Internet Explorer

Servidor webEj.: Servidor WWW

Protocolo HTTPOtra capa

BD(3

capas)

DAD (98) 19

Envía una petición al servidor y se queda esperando por una respuesta.

Su tiempo de vida es finito pues una vez que son servidas sus solicitudes, termina su trabajo.

DAD (98) 20

Es cualquier programa que ofrece un servicio que se puede obtener en una red.

Acepta la petición desde la red, realiza el servicio y devuelve el resultado al solicitante.

DAD (98) 21

http://servidor.dominio:Puerto/{directorio/subdirectorio}/recurso

Servidor: ceis, ntceis, ceisweb.Dominio: .cujae.edu.cu, .com, .itesm.mx, .govPuerto : 80 8080 Recurso: .html, .php, .ppt, .doc

Ejemplo: http://ceis/educative/index.php http://www.amazon.com/exec/obidos/ASIN/0131752421/deitelassociatin

DAD (98) 22

Del lado del cliente Programas interpretados

(JavaScript, VBScript) que manipulan eventos, etc.

Programas ejecutados (Applets, Plug-ins, ActiveX) que muestran documentos de diferentes medios (Audio, Video, Flash)

DAD (98) 23

Del lado del servidor.

–Extensión de servidores web, a través de una nueva capa de procesamiento.

–La capa de procesamiento interpreta la solicitud del cliente.

–El servidor web funciona como intermediario. Servidores lenguajes script

(PHP, ASP, Perl, JSP).

DAD (98) 24

JavaScript

DAD (98) 25

Lo conocido de JavaScript

Objetos y funciones básicos √ Formas de incorporarlo a la página √ Estructuras: Condiciones, Repeticiones. √ Entrada de datos. √ Escritura en documentos. √ (IE != FF) √

DAD (98) 26

Descripción Símbolo

Multiplicación *

División /

Resto de la división entera %

Suma +

Resta -

Incremento ++

Decremento --

DAD (98) 27

Descripción Símbolo

Igualdad ==

Desigualdad !=

Menor que <

Mayor que >

Menor o igual que <=

Mayor o igual que >=

DAD (98) 28

Descripción Símbolo

Negación !

Y &&

O ||

Ejemplo:(a==b) && !(b)

DAD (98) 29

Arreglos en JavaScript

DAD (98) 30

• Los arreglos son base 0.

• Para crear un arreglo sería varArr = new Array (cantElem);

• Para acceder a la cantidad de elementos

cantElem = varArr.length;

varArr[0] accede al

elemento 0

del arreglo varArr.

DAD (98) 31

Arreglos de JavaScript Objeto Array Sintaxis similar a otros lenguajes.

– theArray[ i ] Flexibilidad en el tipo y la inicialización. Pueden tener más de una dimensión. Variantes más declarativas de recorrerlos. Aprenderemos usando casos ejemplos del libro.

Además:

Ejemplos de uso de métodos del objeto Math, etc.

DAD (98) 32

Arreglos en JavaScript

Declaración, inicialización y recorrido

DAD (98) 33

<?xml version = "1.0" encoding = "utf-8"?>… <!-- Fig. 10.3: InitArray.html --><html xmlns = "http://www.w3.org/1999/xhtml"> <head> … <script type = "text/javascript"> <!-- // create (declare) two new arrays var n1 = new Array( 5 ); // allocate five-element Array var n2 = new Array(); // allocate empty Array // assign values to each element of Array n1 for ( var i = 0; i < n1.length; ++i ) n1[ i ] = i; // create and initialize five elements in Array n2 for ( i = 0; i < 5; ++i ) n2[ i ] = i; ….

DAD (98) 34

outputArray( "Array n1:", n1 ); outputArray( "Array n2:", n2 ); // output the heading followed by a two-column table

// containing subscripts and elements of "theArray" function outputArray( heading, theArray ) { document.writeln( "<h2>" + heading + "</h2>" ); document.writeln( "<table border = \"1\"" ); document.writeln( "<thead><th>Subscript</th>" + "<th>Value</th></thead><tbody>" ); // output the subscript and value of each array element

for ( var i = 0; i < theArray.length; i++ ) document.writeln( "<tr><td>" + i + "</td><td>" + theArray[ i ] + "</td></tr>" ); document.writeln( "</tbody></table>" ); } // end function outputArray // --> </script> </head><body></body></html>

DAD (98) 35

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 10.4: InitArray2.html --><!-- Declaring and initializing arrays. --><html xmlns = "http://www.w3.org/1999/xhtml"> <head>

<title>Initializing an Array with a Declaration</title> <style type = "text/css"> table { width: 15em } th { text-align: left } </style> <script type = "text/javascript"> <!--

// Initializer list specifies the number of elements // and a value for each element. var colors = new Array( "cyan", "magenta", "yellow", "black" ); var integers1 = [ 2, 4, 6, 8 ]; var integers2 = [ 2, , , 8 ];

outputArray( "Array colors contains", colors ); outputArray( "Array integers1 contains", integers1 ); outputArray( "Array integers2 contains", integers2 ); …. // --> </script> </head><body></body></html>

DAD (98) 36

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 10.5: SumArray.html --><html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Sum the Elements of an Array</title> <script type = "text/javascript"> <!--

var theArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; var total1 = 0, total2 = 0; // iterates through the elements of the array in order // and adds each element's value to total1 for ( var i = 0; i < theArray.length; i++ ) total1 += theArray[ i ]; document.writeln( "Total using subscripts: " + total1 );

// iterates through the elements of the array using a // for... in statement to add each element's value to total2

for ( var element in theArray ) total2 += theArray[ element ]; document.writeln( "<br />Total using for...in: " + total2 ); // --> </script> </head><body></body></html>

DAD (98) 37

Arreglos en JavaScript

Combinación con uso del objeto Math

DAD (98) 38

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 10.6: RollDie.html --><html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Roll a Six-Sided Die 6000 Times</title> <style type = "text/css"> table { width: 15em } th { text-align: left } </style> <script type = "text/javascript"> <!--

var face; var frequency = [ , 0, 0, 0, 0, 0, 0 ];// leave frequency[0] uninitialized // summarize results

for ( var roll = 1; roll <= 6000; ++roll ) { face = Math.floor( 1 + Math.random() * 6 ); ++frequency[ face ]; } // end for document.writeln( "<table border = \"1\"><thead>" ); document.writeln( "<th>Face</th>" + "<th>Frequency</th></thead><tbody>" ); // generate entire table of frequencies for each face

for ( face = 1; face < frequency.length; ++face ) document.writeln( "<tr><td>"+ face +"</td><td>"+ frequency[ face ] + "</td></tr>" ); document.writeln( "</tbody></table>" ); // --> </script> </head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body></html>

DAD (98) 39

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 10.7: RandomPicture2.html -->

<!-- Random image generation using arrays. --><html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Random Image Generator</title> <style type = "text/css"> table { width: 15em } th { text-align: left } </style> <script type = "text/javascript"> <!--

var pictures = [ "CPE", "EPT", "GPP", "GUI", "PERF", "PORT", "SEO" ]; // pick a random image from the pictures array and displays by // creating an img tag and appending the src attribute to the filename

document.write ( "<img src = \"" + pictures[ Math.floor( Math.random() * 7 ) ] + ".gif\" />" ); // --> </script> </head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body></html>

DAD (98) 40

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><!-- Fig. 10.8: PassArray.html --> <!-- Passing arrays and individual array elements to functions. --><html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Passing arrays and individual array elements to functions</title> <script type = "text/javascript"> <!--

var a = [ 1, 2, 3, 4, 5 ]; document.writeln( "<h2>Effects of passing entire " + "array by reference</h2>" );

outputArray( "Original array: ", a ); modifyArray( a ); // array a passed by reference outputArray( "Modified array: ", a ); // outputs heading followed by the contents of "theArray"

function outputArray( heading, theArray ) { document.writeln( heading + theArray.join( " " ) + "<br />" ); } // end function outputArray

// function that modifies the elements of an array

function modifyArray( theArray ) { for ( var j in theArray ) theArray[ j ] *= 2; } // end function modifyArray // --> </script> </head><body></body></html>

DAD (98) 41

Arreglos en JavaScript

Paso de arreglos por referencia y por valor

DAD (98) 42

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 10.8: PassArray.html --> <!-- Passing arrays and individual array elements to functions. --><html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Passing arrays and individual array elements to functions</title> <script type = "text/javascript"> <!-- var a = [ 1, 2, 3, 4, 5 ]; document.writeln( "<h2>Effects of passing entire " + "array by reference</h2>" ); outputArray( "Original array: ", a ); modifyArray( a ); // array a passed by reference outputArray( "Modified array: ", a );

document.writeln( "<h2>Effects of passing array element by value " +“</h2>a[3] before modifyElement: " + a[ 3 ] ); modifyElement( a[ 3 ] ); // array element a[3] passed by value

document.writeln( "<br />a[3] after modifyElement: " + a[ 3 ] ); … // function that modifies the value passed

function modifyElement( e ) { e *= 2; // scales element e only for the duration of the function document.writeln( "<br />value in modifyElement: " + e ); } // end function modifyElement // --> </script> </head><body></body></html>

DAD (98) 43

Arreglos en JavaScript

Ordenamiento y búsqueda

DAD (98) 44

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 10.9: Sort.html --><!-- Sorting an array with sort. --><html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Sorting an Array with Array Method sort</title> <script type = "text/javascript"> <!--

var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; document.writeln( "<h1>Sorting an Array</h1>" );

outputArray( "Data items in original order: ", a ); a.sort( compareIntegers ); // sort the array outputArray( "Data items in ascending order: ", a ); // output the heading followed by the contents of theArray

function outputArray( heading, theArray ) { document.writeln( "<p>" + heading + theArray.join( " " ) + "</p>" ); } // end function outputArray // comparison function for use with sort

function compareIntegers( value1, value2 ) { return parseInt( value1 ) - parseInt( value2 ); } // end function compareIntegers // --> </script> </head><body></body></html>

DAD (98) 45

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 10.10: LinearSearch.html -->

<!-- Linear search of an array. --><html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Linear Search of an Array</title> <script type = "text/javascript"> <!--

var a = new Array( 100 ); // create an Array // fill Array with even integer values from 0 to 198 for ( var i = 0; i < a.length; ++i ) a[ i ] = 2 * i;

……

DAD (98) 46

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 10.10: LinearSearch.html --><!-- Linear search of an array. --><html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Linear Search of an Array</title> <script type = "text/javascript"> <!--

…. // function called when "Search" button is pressed

function buttonPressed() { var inputVal = document.getElementById( "inputVal" ); var result = document.getElementById( "result" ); var searchKey = inputVal.value; //leer de objeto var element = linearSearch( a, parseInt( searchKey ) ); if ( element != -1 ) result.value = "Found value in element " + element; else result.value = "Value not found"; // escribir en objeto } // end function buttonPressed …

DAD (98) 47

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 10.10: LinearSearch.html --><!-- Linear search of an array. -->… function buttonPressed() { … } // end function buttonPressed // Search "theArray" for the specified "key" value

function linearSearch( theArray, key ) { // iterates through each element of the array in order for ( var n = 0; n < theArray.length; ++n ) if ( theArray[ n ] == key ) return n; return -1; } // end function linearSearch // --> </script> </head> <body>

<form action = ""> <p>Enter integer search key<br /> <input id = "inputVal" type = "text" /> <input type = "button" value = "Search" onclick = "buttonPressed()" /> <br /></p>

<p>Result<br /> <input id = "result" type = "text" size = "30" /> </p> </form> </body></html>

Ver 10.11// binary search function

DAD (98) 48

Arreglos en JavaScript

Bidimensionales y formularios

DAD (98) 49

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN“ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 10.13: InitArray3.html --> <!-- Initializing multidimensional arrays. --><html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Initializing Multidimensional Arrays</title> <script type = "text/javascript"> <!--

var array1 = [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]; // two rows var array2 = [ [ 1, 2 ], [ 3 ], [ 4, 5, 6 ] ]; // three rows outputArray( "Values in array1 by row", array1 ); outputArray( "Values in array2 by row", array2 ); function outputArray( heading, theArray ) { document.writeln( "<h2>" + heading + "</h2><pre>" ); // iterates through the set of one-dimensional arrays

for ( var i in theArray ) { // iterates through the elements of each one-dimensional array

for ( var j in theArray[ i ] ) document.write( theArray[ i ][ j ] + " " ); document.writeln( "<br />" ); } // end for document.writeln( "</pre>" ); } // end function outputArray // --> </script> </head><body></body></html>

DAD (98) 50

<?xml version = "1.0" encoding = "utf-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 10.14: quiz.html -->

<!-- Online quiz graded with JavaScript. -->

<html xmlns = "http://www.w3.org/1999/xhtml">

<head>

<title>Online Quiz</title>

<script type = "text/JavaScript">

function checkAnswers()

{ var myQuiz = document.getElementById( "myQuiz" );

// determine whether the answer is correct

if ( myQuiz.elements[ 1 ].checked )

alert( "Congratulations, your answer is correct" );

else // if the answer is incorrect

alert( "Your answer is incorrect. Please try again" );

} // end function checkAnswers </script>

</head>

DAD (98) 51

<?xml version = "1.0" encoding = "utf-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN“ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 10.14: quiz.html --> <head> … </head>

<body> <form id = "myQuiz" onsubmit = "checkAnswers()" action = ""> <p>Select the name of the tip that goes with the image shown:<br /> <img src="EPT.gif" alt="mystery tip"/> <br /> <input type = "radio" name = "radiobutton" value = "CPE" /> <label>Common Programming Error</label> <input type = "radio" name = "radiobutton" value = "EPT" /> <label>Error-Prevention Tip</label> <input type = "radio" name = "radiobutton" value = "PERF" /> <label>Performance Tip</label> <input type = "radio" name = "radiobutton" value = "PORT" /> <label>Portability Tip</label><br /> <input type = "submit" name = "submit" value = "Submit" /> <input type = "reset" name = "reset" value = "Reset" /> </p> </form> </body></html>

DAD (98) 52

Conclusiones sobre Arreglos de JavaScript

Objeto Array Sintaxis similar a otros lenguajes. Flexibilidad en el tipo y la inicialización. Pueden tener más de una dimensión. Variantes más declarativas de recorrerlos.

Además:

Ejemplos de uso de métodos del objeto Math, etc.

DAD (98) 53

Objetos en JavaScript

DAD (98) 54

Objetos en JavaScript

Es un lenguaje basado en objetos. Ejemplo: Math, Array, document, window Cada uno puede tener métodos y atributos. Se pueden crear instancias de ellos para

utilizarlos en cada uno de los programas.

DAD (98) 55

• Math.

• Array.

• String.

• Date.

• Boolean.

• Number.

Todos los tipos de objetos comienzan con mayúscula.

Cada objeto tiene un conjunto de métodos definidos como funciones de la forma: objeto.funcion();

DAD (98) 56

CharAt(n): devuelve el carácter ubicado en la posición n.

length: devuelve la longitud de la cadena que la invoca.

index0f(cadena2): busca la cadena2 en la cadena que invoca el método. Si la encuentra, devuelve la posición, si no devuelve -1.

substr(indice,n): devuelve una parte de la cadena contando n caracteres a partir de la posición indice.

substring(indice1, indice2): devuelve la subcadena comprendida entre las posiciones indice1, indice2.

toLowerCase(): transforma la cadena a minúsculas.

toUpperCase(): transforma la cadena a mayúsculas.

DAD (98) 57

• Obtiene fecha y hora del reloj del sistema

Ejemplo:fecha_hoy = new Date();

• Métodos: getTime();

getYear();

getMonth();

getDate();

getHours();

getMinutes();

getSeconds();

getDay();

DAD (98) 58

Utilizando el nombre como literal dentro de corchetes–document.forms['form1']

Utilizando el número de orden dentro de corchetes–document.forms[0]

Utilizando el nombre–document.form1

DAD (98) 59

location: permite conocer o especificar la dirección URL.

Ejemplo: Redirigir el navegador a la página de google:

window.location.href = “http://www.google.com”;

open(): permite abrir nuevas ventanas con una URL, un nombre y una serie de características dadas.

Ejemplo:

window.open(“http://nombre_sitio”, “título”, “características”);

close(): cierra la ventana actual.

DAD (98) 60

El navegador crea un objeto document por cada página HTML

Métodos– write(): Escribe una o más expresiones

HTML en la ventana (window) especificada– ...

Propiedades– forms: Arreglo que contiene una entrada

por cada formulario del documento– ...

DAD (98) 61

El navegador crea un objeto de este tipo para cada formulario del documento

Métodos

– reset: Simula el clic sobre el botón restablecer

–submit: Envía el formularioPropiedades

–elements: Arreglo de los elementos del formulario

– length: Cantidad de elementos

DAD (98) 62

Objetos en JavaScript

Objetos para procesar cadenas de texto.

(vistazo rápido)

DAD (98) 63

?xml version = "1.0" encoding = "utf-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 11.4: CharacterProcessing.html --> <!-- String methods …. --><html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Character Processing Methods</title> <script type = "text/javascript">

<!--

var s = "ZEBRA"; var s2 = "AbCdEfG"; document.writeln( "<p>Character at index 0 in '" + s + "' is " + s.charAt( 0 ) ); document.writeln( "<br />Character code at index 0 in '" + s + "' is " + s.charCodeAt( 0 ) + "</p>" ); document.writeln( "<p>'"+ String.fromCharCode( 87, 79, 82, 68 ) + "' contains character codes 87, 79, 82 and 68</p>" ) document.writeln( "<p>'" + s2 + "' in lowercase is '" + s2.toLowerCase() + "'" ); document.writeln( "<br />'" + s2 + "' in uppercase is '" + s2.toUpperCase() + "'</p>" ); // --> </script> </head><body></body></html>

DAD (98) 64

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN“ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 11.5: SearchingStrings.html --> <!-- String searching with indexOf and lastIndexOf. --><html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Searching Strings with indexOf and lastIndexOf </title> <script type = "text/javascript"> <!-- var letters = "abcdefghijklmnopqrstuvwxyzabcdefghijklm";

function buttonPressed() { var searchForm = document.getElementById( "searchForm" ); var inputVal = document.getElementById( "inputVal" ); searchForm.elements[2].value = letters.indexOf( inputVal.value ); searchForm.elements[3].value = letters.lastIndexOf( inputVal.value ); searchForm.elements[4].value = letters.indexOf( inputVal.value, 12 ); searchForm.elements[5].value = letters.lastIndexOf( inputVal.value, 12 ); } // end function buttonPressed // --> </script> </head>

<body> <form id = "searchForm" action = ""> <h1>The string to search is:<br /> abcdefghijklmnopqrstuvwxyzabcdefghijklm</h1>

<p>Enter substring to search for <input id = "inputVal" type = "text" /> <input name = "search" type = "button" value = "Search“ onclick = "buttonPressed()" /><br /></p>

<p>First occurrence located at index <input id = "first" type = "text" size = "5" /> <br />Last occurrence located at index <input id = "last" type = "text" size = "5" /> <br />First occurrence from index 12 located at index <input id = "first12" type = "text" size = "5" /> <br />Last occurrence from index 12 located at index <input id = "last12" type = "text" size = "5" /> </p> </form> </body> </html>

searchForm.elements["first12"].value= …

DAD (98) 65

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN“ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 11.6: SplitAndSubString.html --> <!-- String object methods split and substring. --> <html xmlns = "http://www.w3.org/1999/xhtml">

<head> <title>String Methods split and substring</title> <script type = "text/javascript"> <!--

function splitButtonPressed()

{ var inputString = document.getElementById( "inputVal" ).value;

var tokens = inputString.split( " " );

document.getElementById( "output" ).value = tokens.join( "\n" );;

document.getElementById( "outputSubstring" ).value =

inputString.substring( 0, 10 );

} // end function splitButtonPressed // --> </script> </head>

<body> <form action = ""> <p>Enter a sentence to split into words<br /> <input id = "inputVal" type = "text" size = "40" /> <input type = "button" value = "Split“ onclick = "splitButtonPressed()" /> </p> <p>The sentence split into words is<br /> <textarea id = "output" rows = "8" cols = "34"> </textarea></p> <p>The first 10 characters of the input string are <input id = "outputSubstring" type = "text" size = "15" /></p> </form> </body> </html>

DAD (98) 66

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN“ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 11.7: MarkupMethods.html --> <!-- String object XHTML markup methods. -->

<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>XHTML Markup Methods of the String Object</title>

<script type = "text/javascript"> <!-- var anchorText = "This is an anchor"; var fixedText = "This is monospaced text"; var linkText = "Click here to go to anchorText"; var strikeText = "This is strike out text"; var subText = "subscript"; var supText = "superscript"; document.writeln( anchorText.anchor( "top" ) ); document.writeln( "<br />" + fixedText.fixed() ); document.writeln( "<br />" + strikeText.strike() ); document.writeln("<br />This is text with a " + subText.sub() ); document.writeln("<br />This is text with a " + supText.sup() ); document.writeln( "<br />" + linkText.link( "#top" ) ); // --> </script> </head><body></body></html>

Web Developer (FireFox)

DAD (98) 67

Objetos en JavaScript

Fechas

(vistazo rápido)

DAD (98) 68

<?xml version = "1.0" encoding = "utf-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 11.9: DateTime.html -->

<!-- Date and time methods of the Date object. -->

<html xmlns = "http://www.w3.org/1999/xhtml">

<head>

<title>Date and Time Methods</title>

<script type = "text/javascript">

<!--

var current = new Date();

document.writeln(

"<h1>String representations and valueOf</h1>" );

document.writeln( "toString: " + current.toString() +

"<br />toLocaleString: " + current.toLocaleString() +

"<br />toUTCString: " + current.toUTCString() +

"<br />valueOf: " + current.valueOf() );

….

DAD (98) 69

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN“ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 11.9: DateTime.html -->

…..

document.writeln(

"<h1>Get methods for local time zone</h1>" );

document.writeln( "getDate: " + current.getDate() +

"<br />getDay: " + current.getDay() +

"<br />getMonth: " + current.getMonth() +

"<br />getFullYear: " + current.getFullYear() +

"<br />getTime: " + current.getTime() +

"<br />getHours: " + current.getHours() +

"<br />getMinutes: " + current.getMinutes() +

"<br />getSeconds: " + current.getSeconds() +

"<br />getMilliseconds: " + current.getMilliseconds() +

"<br />getTimezoneOffset: " + current.getTimezoneOffset() );

DAD (98) 70

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN“ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 11.9: DateTime.html -->

…..

document.writeln("<h1>Specifying arguments for a new Date</h1>" );

var anotherDate = new Date( 2007, 2, 18, 1, 5, 0, 0 );

document.writeln( "Date: " + anotherDate );

document.writeln( "<h1>Set methods for local time zone</h1>" );

anotherDate.setDate( 31 );

anotherDate.setMonth( 11 );

anotherDate.setFullYear( 2007 );

anotherDate.setHours( 23 );

anotherDate.setMinutes( 59 );

anotherDate.setSeconds( 59 );

document.writeln( "Modified date: " + anotherDate ); // -->

</script>

</head><body></body>

</html>

DAD (98) 71

Objetos en JavaScript

Ventanas

DAD (98) 72

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 11.13: window.html -->……

DAD (98) 73

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 11.13: window.html --><!-- Using the window object to create and modify child windows. --><html xmlns = "http://www.w3.org/1999/xhtml"><head><title>Using the Window Object</title><script type = "text/javascript">

<!--

var childWindow; // variable to control the child window function createChildWindow() { var toolBar; var menuBar; var scrollBars; if ( document.getElementById( "toolBarCheckBox" ).checked ) toolBar = "yes"; else toolBar = "no"; if ( document.getElementById( "menuBarCheckBox" ).checked ) menuBar = "yes"; else menuBar = "no"; if ( document.getElementById( "scrollBarsCheckBox" ).checked ) scrollBars = "yes"; else scrollBars = "no"; childWindow = window.open( "", "", ",toolbar = " + toolBar + ",menubar = " + menuBar + ",scrollbars = " + scrollBars ); document.getElementById( "closeButton" ).disabled = false; document.getElementById( "modifyButton" ).disabled = false; document.getElementById( "setURLButton" ).disabled = false; } // end function createChildWindow…

DAD (98) 74

11.13

function modifyChildWindow() { if ( childWindow.closed ) alert( "You attempted to interact with a closed window" ); else childWindow.document.write( document.getElementById( "textForChild" ).value ); } // end function modifyChildWindow function closeChildWindow() { if ( childWindow.closed ) alert( "You attempted to interact with a closed window" ); else childWindow.close(); document.getElementById( "closeButton" ).disabled = true; document.getElementById( "modifyButton" ).disabled = true; document.getElementById( "setURLButton" ).disabled = true; } // end function closeChildWindow…

DAD (98) 75

11.13 …

// set the URL of the child window to the URL

// in the parent window's myChildURL

function setChildWindowURL()

{

if ( childWindow.closed )

alert( "You attempted to interact with a closed window" );

else

childWindow.location =

document.getElementById( "myChildURL" ).value;

} // end function setChildWindowURL

//-->

</script>

</head>

DAD (98) 76

11.13… <body> <h1>Hello, this is the main window</h1> <p>Please check the features to enable for the child window<br/>

<input id = "toolBarCheckBox" type = "checkbox" value = "" checked = "checked" /> <label>Tool Bar</label> <input id = "menuBarCheckBox" type = "checkbox" value = "" checked = "checked" /> <label>Menu Bar</label> <input id = "scrollBarsCheckBox" type = "checkbox" value = "" checked = "checked" /> <label>Scroll Bars</label></p> <p>Please enter the text that you would like to display in the child window<br/>

<input id = "textForChild" type = "text" value = “<h1>Hello, I am a child window.</h1> " /> <input id = "createButton" type = "button“ value = "Create Child Window" onclick = "createChildWindow()" /> <input id= "modifyButton" type = "button" value = "Modify Child Window“ onclick = "modifyChildWindow()" disabled = "disabled" /> <input id = "closeButton" type = "button" value = "Close Child Window“ onclick = "closeChildWindow()" disabled = "disabled" /></p> <p>The other window's URL is: <br/>

<input id = "myChildURL" type = "text" value = "./" /> <input id = "setURLButton" type = "button" value = "Set Child URL“ onclick = "setChildWindowURL()" disabled = "disabled" /></p></body> </html>

DAD (98) 77

Objetos en JavaScript

Cookies

DAD (98) 78

Lo recordará hasta que expiren las cookies

DAD (98) 79

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN“ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 11.15: cookie.html --> <!-- Using cookies to store user identification data. -->

<html xmlns = "http://www.w3.org/1999/xhtml">

<head> <title>Using Cookies</title> <script type = "text/javascript"> <!-- var now = new Date(); // current date and time

var hour = now.getHours(); // current hour (0-23)

var name; if ( hour < 12 ) // determine whether it is morning

document.write( "<h1>Good Morning, " ); else { hour = hour - 12; // convert from 24-hour clock to PM time

// determine whether it is afternoon or evening if ( hour < 6 ) document.write( "<h1>Good Afternoon,

" ); else document.write( "<h1>Good Evening, " ); } // end else…

DAD (98) 80

.. 11.15: cookie.html --> <!-- Using cookies to store user identification data. --> … // determine whether there is a cookie

if ( document.cookie ) { // convert escape characters in the cookie string to their English notation

var myCookie = unescape( document.cookie ); // split the cookie into tokens using = as delimiter var cookieTokens = myCookie.split( "=" ); // set name to the part of the cookie that follows the = sign

name = cookieTokens[ 1 ]; } // end if else { // if there was no cookie, ask the user to input a name

name = window.prompt( "Please enter your name", "Paul" ); // escape special characters in the name string and add name to the cookie

document.cookie = "name=" + escape( name ); } // end else document.writeln( name + ", welcome to JavaScript programming!

</h1>" ); document.writeln( "<a href = 'javascript:wrongPerson()'>" + "Click here if you are not " + name + "</a>" );…

Para que no expire al cerrar la sesión (cierra el navegador):

document.cookie = "name=" + escape( name )

+ "; expires= 01-Jan-2010 00:00:01 GMT";

DAD (98) 81

<!-- Fig. 11.15: cookie.html --> <!-- Using cookies to store user identification data. -->

… // reset the document's cookie if wrong person

function wrongPerson() { // reset the cookie document.cookie= "name=null;" + " expires=Thu, 01-Jan-95 00:00:01 GMT"; // reload the page to get a new name after removing the cookie

location.reload(); } // end function wrongPerson

// --> </script> </head> <body> <p>Click Refresh (or Reload) to run the script again</p> </body></html>

DAD (98) 82

Un ejemplo integrador en JavaScript

Fig. 11.16 y 11.17

DAD (98) 83

DAD (98) 84

DAD (98) 85

DAD (98) 86

<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 11.16: final.html --> <!-- Rich welcome page using several JavaScript concepts. -->

<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Putting It All Together</title> <script type = "text/javascript"> <!-- var now = new Date(); // current date and time var hour = now.getHours(); // current hour var pictures = [ "CPE", "EPT", "GPP", "GUI", "PERF", "PORT", "SEO" ]; // array with the quotes that will be randomly selected var quotes = [

"Form ever follows function.<br/>" + " Louis Henri Sullivan", "E pluribus unum." + " (One composed of many.) <br/> Virgil", "Is it a" + " world to hide virtues in?<br/> William Shakespeare" ];…

DAD (98) 87

<!-- Fig. 11.16: final.html -->

// write the current date and time to the web page document.write( "<p>" + now.toLocaleString() + "<br/></p>" ); // determine whether it is morning if ( hour < 12 ) document.write( "<h2>Good Morning, " ); else { hour = hour - 12; // convert from 24-hour clock to PM time

// determine whether it is afternoon or evening if ( hour < 6 ) document.write( "<h2>Good Afternoon, " ); else document.write( "<h2>Good Evening, " ); } // end else…

DAD (98) 88

<!-- Fig. 11.16: final.html -->…

// determine whether there is a cookie

if ( document.cookie ) { // convert escape characters in the cookie string to their English notation

var myCookie = unescape( document.cookie ); // split the cookie into tokens using = as delimiter var cookieTokens = myCookie.split( "=" ); // set name to the part of the cookie that follows the = sign

name = cookieTokens[ 1 ]; } // end if else { // if there was no cookie, ask the user to input a name

name = window.prompt( "Please enter your name", "Paul" ); // escape special characters in the name string and add name to the cookie

document.cookie = "name =" + escape( name ); } // end else…

DAD (98) 89

<!-- Fig. 11.16: final.html -->

// write the greeting to the page

document.writeln( name + ", welcome to JavaScript programming!</h2>" );

// write the link for deleting the cookie to the page

document.writeln( "<a href = \"javascript:wrongPerson()\">" + "Click here if you are not " + name + "</a><br/>" ); // write the random image to the page document.write ( "<img src = \"" + pictures[ Math.floor( Math.random() * 7 ) ] + ".gif\" /> <br/>" ); // write the random quote to the page document.write ( quotes[ Math.floor( Math.random() * 3 ) ] );

DAD (98) 90

<!-- Fig. 11.16: final.html -->…

// create a window with all the quotes in it function allQuotes() { // create the child window for the quotes var quoteWindow = window.open( "", "", "resizable=yes, " + "toolbar=no, menubar=no, status=no, location=no," + " scrollBars=yes" ); quoteWindow.document.write( "<p>" ) // loop through all quotes and write them in the new window

for ( var i = 0; i < quotes.length; i++ ) quoteWindow.document.write( ( i + 1 ) + ".) " + quotes[ i ] + "<br/><br/>");

// write a close link to the new window

quoteWindow.document.write( "</p><br/> <a href = " + "\"javascript:window.close()\"> Close this window </a>" ) } // end function allQuotes…

DAD (98) 91

<!-- Fig. 11.16: final.html -->

// reset the document's cookie if wrong person

function wrongPerson() { // reset the cookie document.cookie= "name=null;" + " expires=Thu, 01-Jan-95 00:00:01 GMT"; // reload the page to get a new name after removing the cookie

location.reload(); } // end function wrongPerson

// open a new window with the quiz2.html file in it

function openQuiz() { window.open( "quiz2.html", "", "toolbar = no, " + "menubar = no, scrollBars = no" ); } // end function openQuiz // --> </script>

</head> …

DAD (98) 92

<!-- Fig. 11.16: final.html -->

<body> <p><a href = "javascript:allQuotes()">View all quotes</a></p> <p id = "quizSpot"> <a href = "javascript:openQuiz()">Please take our quiz </a></p>

<script type = "text/javascript"> // variable that gets the last modification date and time

var modDate = new Date( document.lastModified ); // write the last modified date and time to the page document.write ( "This page was last modified " + modDate.toLocaleString() ); </script></body></html>

DAD (98) 93

<?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN“ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 11.17: quiz2.html --> <!-- Online quiz in a child window. --><html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Online Quiz</title> <script type = "text/JavaScript"> <!-- function checkAnswers() { if (document.getElementById( "myQuiz").elements[1].checked ) window.opener.document.getElementById( "quizSpot" ).innerHTML = "Congratulations, your answer is correct"; else // if the answer is incorrect window.opener.document.getElementById( "quizSpot" ).innerHTML = "Your answer is incorrect. " + "Please try again <br /> <a href =" + "\"JavaScript:openQuiz()\"> Please take our quiz</a>" window.opener.focus();

window.close(); } // end function checkAnswers //--> </script> </head> …

DAD (98) 94

… <!-- Fig. 11.17: quiz2.html --> <!-- Online quiz in a child window. -->…

<body>

<form id = "myQuiz" action = "javascript:checkAnswers()"> <p>Select the name of the tip that goes with the image shown:<br /> <img src = "EPT.gif" alt = "mystery tip"/> <br /> <input type = "radio" name = "radiobutton" value = "CPE" /> <label>Common Programming Error</label> <input type = "radio" name = "radiobutton" value = "EPT" /> <label>Error-Prevention Tip</label> <input type = "radio" name = "radiobutton" value = "PERF" /> <label>Performance Tip</label> <input type = "radio" name = "radiobutton" value = "PORT" /> <label>Portability Tip</label><br /> <input type = "submit" name = "Submit" value = "Submit" /> <input type = "reset" name = "reset" value = "Reset" /> </p> </form> </body> </html>

DAD (98) 95

Conclusiones

El paradigma de software distribuido es el resultado de una tendencia en la computación.

JavaScript cuenta con otras potencialidades que no se habían visto hasta ahora para trabajar con:

– Arreglos

– Objetos

DAD (98) 96

Deitel, Harvey M.-, Internet and the World Wide Web : how to program / H.M. Deitel, P.J. Deitel, T.R. Nieto., , Upper Saddle River, N.J. : Prentice Hall 2008

– Cáp. 10, 11. JavaScript Arreglos Objetos

Libro de texto

DAD (98) 97

Próxima actividadDeben traer Deben traer (Para el MARTES 7.1)(Para el MARTES 7.1)::

[ Antes: Valorar unión en equipos ] [ Antes: Valorar unión en equipos ] ¡¿?!¡¿?!

•Rectificar señalamientos anteriores Rectificar señalamientos anteriores ¡!¡!

Incorporar Incorporar JavaScriptJavaScript en al menos una en al menos una página página de su proyectode su proyecto que incluya: que incluya:

•Arreglos: Arreglos: creación creación y y recorridorecorrido

•Objetos: Objetos: Uso de Uso de unouno de los siguientes: de los siguientes: Date, Math, objetos para textoDate, Math, objetos para texto

•Ventajas hijas: Ventajas hijas: abrir, modificar abrir, modificar yy cerrar. cerrar.

•Uso de cookiesUso de cookies

DAD (98) 98

Próxima actividad(Para el MARTES 7.1) (Para el MARTES 7.1) :(10 puntos):(10 puntos)

•Rectificar señalamientos Rectificar señalamientos (2)(2)

Incorporar Incorporar JavaScriptJavaScript en al menos una en al menos una página página de su proyectode su proyecto que incluya: que incluya:

•Arreglos: Arreglos: creación creación y y recorrido recorrido (2)(2)

•Objetos: Objetos: Uso de Uso de unouno de los siguientes: de los siguientes: Date, Math, objetos para texto Date, Math, objetos para texto (2)(2)

•Ventajas hijas: Ventajas hijas: abrir, modificar abrir, modificar yy cerrar cerrar (2)(2)

•Uso de cookies Uso de cookies (2)(2)

top related