230 likes | 249 Views
Client-side. CS 371 Web Application Programming. Web-based Applications. Internet. client. Desktop vs Web-based. traditional desktop applications single user, one location data is stored locally can maintain state as fast as the machine web-based applications
E N D
Client-side CS 371 Web Application Programming
Web-based Applications Internet client
Desktop vs Web-based • traditional desktop applications • single user, one location • data is stored locally • can maintain state • as fast as the machine • web-based applications • data is stored in the cloud • stateless • data sent over public network • as fast as the network/client/server
constraints client-server stateless cacheable layered system code on demand uniform interface REpresentational State Transfer (REST) • software architecture • clients and servers • client sends request when ready for new state • server returns new state with links for new requests HTTP verbs: GET, POST, PUT, etc.
JavaScript • Origins • Syntax and functions • Arrays • Objects • Special features • Accessing the DOM
JavaScript Origins • 1995: Netscape creates LiveScript (quickly changed to JavaScript) • Microsoft introduces VBScript and then Jscript • 1996: Netscape proposes ECMAScript specification as a standard • 1997: ECMA-262 • JavaScript is cross-browser compatible • most incompatibility issues arise in differences in the DOM and CSS
JavaScript - Implementation • scripts can be placed • internally using <script> tags • externally using <script type=“text/javascript” src=“file.js”> • typically put functions in the head section and scripts as needed in the body
JavaScript basic syntax • similar to c/c++, java • semicolons at end of lines are optional • use <!-- \n statements . . . \n //--> to prevent older browsers from displaying javaScript code • comments - use both // and /*…*/ • JavaScript operates in a sandbox, i.e. browser puts a protective wall around code
Operators and control structures • operators are similar to C and Java except == and != work with strings • if, else, switch are just like Java and C • loops - like java including the foreach: • for(var in collection) • objects • uses dot operator for properties and methods • Strings have many Java methods • Date: var myDate = new Date() (date & time) • Math object - like java
JavaScript data types and variables • JavaScript is not strongly typed • data types: • strings (use either “ or ‘) • boolean (false if undefined, null, 0, NaN, null string) • numeric (floating point or integer - limit numbers to 2e31) • scope • using var inside functions is local • global vars declared with var outside function and used inside functions without var
Built-in objects • several built-in objects with helpful information • JavaScript: Array, Boolean, Date, Math, Number, String, RegExp and Global properties and functions • Browser objects: • Window - represents open window • navigator - information about the browser • screen - information about the visitor’ screen • history - URLs visited by user • location - information about current URL
Date • getDate() Returns day of the month (from 1-31) • getDay() Returns the day of the week (from 0-6) • getFullYear() Returns the year (four digits) • getHours() Returns the hour (from 0-23) • getMilliseconds() Returns the milliseconds (from 0-999) • getMinutes() Returns the minutes (from 0-59) • getMonth() Returns the month (from 0-11) • getSeconds() Returns the seconds (from 0-59) • Many, many more…
Number • MAX_VALUE Returns the largest number possible in JavaScript • MIN_VALUE Returns the smallest number possible in JavaScript • toExponential(x) Converts a number into an exponential notation • toFixed(x) Formats a number with x numbers of digits after the decimal point • toPrecision(x) Formats a number to x length • toString() Converts a Number object to a string • valueOf() Returns the primitive value of a Number object
String • charAt() Returns the character at the specified index • concat() Joins two or more strings, and returns a copy of the joined strings • fromCharCode() Converts Unicode values to characters • indexOf() Returns the position of the first found occurrence of a specified value in a string • lastIndexOf() Returns the position of the last found occurrence of a specified value in a string • match() Searches for a match between a regular expression and a string, and returns the matches • replace() Searches for a match between a substring (or reg exp) and a string, and replaces the matched substring with a new substring • search() Searches for a match between a regular expression and a string, and returns the position of the match • slice() Extracts a part of a string and returns a new string • split() Splits a string into an array of substrings • substr() Extracts the characters from a string, beginning at a specified start position, and through the specified number of character • substring() Extracts the characters from a string, between two specified indices • toLowerCase() Converts a string to lowercase letters • toUpperCase() Converts a string to uppercase letters • valueOf() Returns the primitive value of a String object
Arrays • var myArray = new Array(); or • var myArray = [ ]; • var myArray = new Array(‘one’,’two’); • var myArray = [‘one’,’two’]; • var scores = new Array(); • scores[0]=[94,84,79]; • scores[1]=[87,64,90]; • course[‘371’]=‘scripps’; //associative?
Array • concat() Joins two or more arrays, and returns a copy • join() Joins all elements of an array into a string • pop() Removes the last element of an array, and returns it • push() Adds new elements to the end of an array • reverse() Reverses the order of the elements in an array • shift() Removes the first element of an array, and returns it • slice() Selects a part of an array, and returns the new array • sort() Sorts the elements of an array • splice() Adds/Removes elements from an array • toString() Converts an array to a string, and returns the result • unshift() Adds new elements to the beginning of an array, and returns the new length • valueOf() Returns the primitive value of an array
User defined functions • function(a,b) { return a*b; } • parameters do not need types • no return type • anonymous functions: • var f = new Function(“x”,”y”,”return x+y”); • f(6,7); • f(“hello”,”world”);
User Defined Objects • using new Object: • var myObj=new Object(); • myObject.height=12; • using object function: • function userObj(parm){…} • var obj=new userObj(‘oh hey’); • using literal notation: • var myObj={name:”miltie”,age:33…}
Exceptions • runtime errors • try, catch and finally are like java except there is only one catch and object is not typed • use confirm popup to reroute user to other page:window.location="./anotherPage.htm"; • throw - allows programmer to throw except • syntax errors • onerror=handleErr • function handleErr(msg,url,line)
Popups • Used for debugging and user interaction • alert(“hey “+x); //displays info • if(confirm(“is this ok?”)==true) • var age = prompt(“how old are you?”);
Security • browsers restrict what JavaScript can do to prevent hacker attacks on clients • same-origin policy - scripts cannot communicate across domains
Setting cookies • document.cookie=“var=val;expire=expireDays;path=aPath” • example: • var p=“myPassword”; • var exp=new Date()+30; • document.cookie=“pass=“+p+”;expires=“+ exp.toUTCString(); • set expires to yesterday to delete
Getting cookies • cookies are stored as one big string • var i=cookie.indexOf(“pass=“); • if(i>=0){ • var str=cookie.substring(i,cookie.length); • var last=str.indexOf(“;”); • if(last<0) last=str.length; • str=str.substring(0,last).split(“=“); • cookie is in str[1]