1 / 79

Lecture 1: Intro to JavaScript

Course Notes for CS1520 Programming Languages Part B By John C. Ramirez Department of Computer Science University of Pittsburgh. These notes are intended for use by students in CS1520 at the University of Pittsburgh and no one else

elga
Download Presentation

Lecture 1: Intro to JavaScript

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Course Notes forCS1520 Programming LanguagesPart BByJohn C. RamirezDepartment of Computer ScienceUniversity of Pittsburgh

  2. 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: • Programming the World Wide Web, multiple editions, by Robert Sebesta (AW) • JavaScript by Don Gossein (Thomson Learning) • https://developer.mozilla.org/en/JavaScript/Reference • http://www.w3schools.com/jsref/default.asp • http://www.w3.org/TR/XMLHttpRequest/

  3. Lecture 1: Intro to JavaScript • What is JavaScript? • Language developed by Netscape • 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

  4. Lecture 1: JavaScript Basics • How to include JavaScript in html? • JavaScript programs require the <SCRIPT> tag in .html files <script type = "text/javascript"> ACTUAL JavaScript code here </script> • These can appear in either the <HEAD> or <BODY> section of an html document • Functions and code that may execute multiple times is typically placed in the <HEAD> • These are only interpreted when the relevant function or event-handler are called

  5. Lecture 1: JavaScript Basics • Code that needs to be executed only once, when the document is first loaded is placed in the <BODY> • Some browsers may not support scripting (i.e. have it turned off) • To be safe, you could put your scripts in html comments as specified in Sebesta text • This way browsers that do not recognize JavaScript will look at the programs as comments • Note that, unlike PHP scripts, JavaScripts are visible in the client browser • Since they are typically acting only on the client, this is not a problem

  6. Lecture 1: JavaScript Basics • However, if we want to prevent the script itself from being (easily) seen, we can upload our JavaScript from a file • This will show only the upload tag in our final document, not the JavaScript from the file • Use the src option in the tag <script type = "text/javascript" src = "bogus.js"></script> • However, the source is likely still not really hidden • In a temp folder somewhere on computer and can be seen with a utility like FireBug • Thus you should not "hardcode" into Javascript anything that you don't want the client to see

  7. 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>

  8. Lecture 1: JavaScript Variables • JavaScript variables have no types • Type is determined dynamically, based on the value stored • This is becoming familiar! • The typeof operator can be used to check type of a variable • Declarations are made using the var keyword • Can be implicitly declared, but not advisable • Declarations outside of any function are global • Declarations within a function are local to that function • Variables declared but not initialized have the value undefined

  9. Lecture 1: JavaScript Variables • Variable identifiers are similar to those in other languages (ex: Java) • Cannot use a keyword • Must begin with a letter, $, or _ • Followed by any sequence of letters, $, _ or digits • Case sensitive

  10. Lecture 1: JavaScript Expressions • Numeric operators in JavaScript are similar to those in most languages +, –, *, /, %, ++, -- • Precedence and associativity are also fairly standard • Strings • Have the + operator for concatenation • Have a number of methods to do typical string operations • charAt, indexOf, toLowerCase, substring • Looks kind of like Java – intentionally

  11. Lecture 1: JavaScript Expressions • Similar to PHP, with mixed number/string type expressions, JavaScript will coerce if it can • If operator is + and an operand is string, it will always coerce other to string • If operator is arithmetic, and string value can be coerced to a number it will do so • If string is non-numeric, result is NaN (NotaNumber) • We can also explicitly convert the string to a number using parseInt and parseFloat • Again looks like Java • See ex2.html

  12. 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

  13. Lecture 1: Control Statements • Control statements similar to Java • if, while, do, for, switch • Variables declared in for loop header are global to the rest of the script • Functions • 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

  14. Lecture 1: Functions • Functions execute when they are called, just as in any language • To allow this, function code should be in the <HEAD> section of the .html file • Variables declared in a function are local to the function • Parameters are all value • No parameter type-checking • Numbers of formal and actual parameters do not have to correspond • Extra actual parameters are ignored • Extra formal parameters are undefined • All actual parameters can be accessed regardless of formal parameters by using the arguments array • See ex3.html

  15. Lecture 1: Array Objects • More relaxed version of Java arrays • Size can be changed and data can be mixed • Cannot use arbitrary keys as with PHP arrays • Creating arrays • Using the new operator and a constructor with multiple arguments var A = new Array("hello", 2, "you"); • Using the new operator and a constructor with a single numeric argument var B = new Array(50); • Using square brackets to make a literal var C = ["we", "can", 50, "mix", 3.5, "types"];

  16. Lecture 1: Array Objects • 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

  17. Lecture 1: Array Objects • Array Methods • 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

  18. Lecture 1: Array Objects • These operations are invoked via method calls, in an object-based way • Also many, such as sort and reverse are mutators, affecting the array itself • JavaScript also has 2-dimensional arrays • Created as arrays of arrays, but references are not needed • see ex4.html

  19. Lecture 2: JavaScript Objects • JavaScript is an object-based language • It is NOT object-oriented • It has and uses objects, but does not support some features necessary for object-oriented languages • Class inheritance and polymorphism not supported • They can be “faked” but are not really there • http://www.webreference.com/js/column79/ • http://www.webreference.com/js/column80/

  20. Lecture 2: JavaScript Objects • JavaScript objects are actually represented as property-value pairs • Actually similar to keyed arrays in PHP • The object is analogous to the array, and the properties are analogous to the keys • However, the property values can be data or functions (methods) • Ex: var my_tv = new Object(); my_tv.brand = ”Samsung"; my_tv.size = 46; my_tv.jacks = new Object(); my_tv.jacks.input = 5; my_tv.jacks.output = 2;

  21. Lecture 2: JavaScript Objects • Note that the objects can be created and their properties can be changed dynamically • Also, objects all have the same data type – object • We can write constructor functions for objects if we'd like, but these do not create new data types – just easy ways of uniformly initializing objects function TV(brand, size, injacks, outjacks) { this.brand = brand; this.size = size; this.jacks = new Object(); this.jacks.input = injacks; this.jacks.output = outjacks; } … var my_tv = new TV(”Samsung”, 46, 5, 2);

  22. Lecture 2: 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

  23. Lecture 2: Javascript Objects • We can do a lot with Javascript objects • Even though Javascript is not truly object-oriented, we can program in an object-based way • Encapsulating data and methods within objects • Utilizing methods for operations on the objects • See ex6.html • We will be using Javascript objects a lot with client-side programming

  24. Lecture 2: Regular Expressions • JavaScript regular expression handling is also based on that in Perl • The patterns and matching procedures are the same as in Perl, Java and PHP (PCRE) • However, now the functions are methods within a string object (similar to Java) var s = "a man, a plan, a canal: panama"; var loc = s.search(/plan/); var matches1 = s.match(/an/g); var matches2 = s.match(/\w+/g); var matches3 = s.split(/\W+/); s = s.replace(/\W/g, "-"); • Note that match is similar to the PHP match function • Returns the matched pieces as opposed to the non-matched pieces (that split returns) • See ex7.html

  25. Lecture 2: DOM • The Document Object Model • Developed by W3C (World-Wide Web Consortium) • http://www.w3c.org/DOM/ • Specifies the contents of Web documents in an object-oriented way • Allows programming languages to access and manipulate the components of documents • Defined at a high level so that a variety of languages can be used with it • It is still being updated / revised • We are not even scratching the surface here

  26. Lecture 2: DOM • History / Idea • HTML and XML documents consist of tags • Well-formatted documents (required in XHTML and XML) can be viewed as a tree • Ex: http://www.w3schools.com/htmldom/default.asp • DOM provides a language-independent, object-based model for accessing / modifying and adding to these tags • DOM 0 • Not formally specified by W3C but includes a lot of useful functionality

  27. Lecture 2: DOM • DOM 1, 2, 3 • Formal specifications of model and functionality • Each builds on / improves previous • Unfortunately there are still compatibility issues with browsers • IE through IE8 does not fully support DOM 2 • It has its own syntax for event attachment • IE9 does support DOM 2 but until all older versions go away the problem still exists

  28. Lecture 2: Events • With documents DOM specifies events and event handlers • Event model is similar to the one used in Java • Different parts of a document have different events associated with them • We can define handlers to react to these events • These allow us to "interact" with and add "dynamic content" to web documents • Ex: Can preprocess form elements • Ex: Can load / update / change what is displayed in response to an event

  29. Lecture 2: DOM and Events • document refers to the top-level document • Each document has access to its properties and to the components that are declared within it • Ex: title, URL, forms[], applets[], images[] • Attributes with IDs can also be specified by ID (from DOM 1) • Once we know the components, events and event-handlers, we can write JavaScript programs to process Web pages on the client-side • Client computers are typically less busy than servers, so whatever we can do at the client will be helpful overall

  30. Lecture 2: DOM and Events • Ex: Checking form correctness before it is submitted • In HTML documents events are specified through tag attributes • Within the tag identifying an HTML component, we can specify in an attribute how the component reacts to various events • See Sebesta Table 5.1 for events and tag attributes and Table 5.2 for the tags that have a given attribute • Similar in idea to Java, we assign event handling code to the tag attributes, and the code executes when the event occurs

  31. Lecture 2: Events • We can also attach events in Javascript • In DOM 0, events are attached in an “inline” way: • Ex: theElement.onclick = functionName • In DOM 2, a more flexible event model was developed, so that more than one handler could be attached to the same event: • Ex: theElement.addEventListener(type, fn, opt) • Where opt is a boolean to determine if the event is “captured” or “bubbles” • See: http://en.wikipedia.org/wiki/DOM_Events • Unfortunately, IE (up through IE8) does not use DOM 2 • It has its own, similar model

  32. Lecture 2: DOM and Events • Ex: Event mouseoveroccurs when the mouse is place over a displayed element • Elements that allow for the mouseover event have the attribute onmouseover • In HTML or Javascript, the programmer assigns a function call to the attribute, so that when the event occurs the function is called <input type = "radio" name = "choice" value = "1" onmouseover = "showChoice(1)"> • We can define showChoice however we'd like • ex: alert("You are about to choose Choice 1");

  33. Lecture 2: Example: Pre-processing a Form • A very common client-side operation is pre-processing a form • Ensure that fields are filled and formatted correctly, so server does not have to • Saves load on the server, saves time and saves bandwidth • We can check a form overall by using the attribute onsubmit • We can put it right into the form as an attribute • Or we can assign the attribute through the document object in Javascript

  34. Lecture 2: Example: Pre-processing a form • We can check individual components as they are entered as well • Ex: <input type = "text"> has the onchange attribute • Triggered when contents are changed and focus changes • Ex: <input type = "radio"> has the onclick attribute • Triggered when the radio button is clicked with the mouse • 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!

  35. Lecture 3: Processing Multiple Forms and Multiple Submits • Web pages can also have multiple forms • These can be handled both on the client side using JavaScript and on the server side • Idea is to identify which form has been submitted and respond accordingly • See mform.html and mform.php • Similarly, we can have multiple submits of a single form • See also msub.html and msub.php • One more example demonstrating DOM • See ex9.html

  36. Lecture 3: AJAX • Asynchronous JavaScript And XML • This is technique that was coined in Feb. 2005 but that has been used (more or less) for quite a while before that • It allows the client and the server to communicate without requiring a "hard" submit and page refresh • In particular, the page can be updated without reloading it in its entirety • Makes the user interface for a Web app. appear more like that of a desktop app • See: http://en.wikipedia.org/wiki/AJAX http://developer.mozilla.org/en/docs/AJAX

  37. Lecture 3: AJAX • Let's look at a few details and some simple examples • You may also want to research it on your own • AJAX centers around the XMLHttpRequest object • This object allows the client to connect to a server and to respond to the reply once it has become available • There is a lot that can be done with this, especially in conjunction with XML and JSON – we will mention these later

  38. Lecture 3: AJAX • It is a bit tricky to use, and is not consistent across all browsers (esp. older versions) • However, once you get the hang of it, it can be a very useful tool and it is REALLY COOL! • Basic Idea: • Programmer creates an instance of an XMLHttpRequest object • Several useful attributes and methods are associated with this object: • see:http://www.w3.org/TR/XMLHttpRequest/ • Let's look at a few of them to see how they work together

  39. 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

  40. 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

  41. 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

  42. Lecture 3: AJAX • 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 • Let's look at a simple example • MozDemo.html – from Mozilla devel. site • Just demonstrates the basics of AJAX

  43. Lecture 3: AJAX • Ok, that example was very simple • In a real situation, the response from the server will require us to update our local page, possibly in a significant way • How to do this? document.writeln()? • Only works during initial rendering of the page • Using DOM? Yes! • First we will look simply at HTML • Later we will look at XML and JSON • See: http://www.w3schools.com/htmldom/default.asp • Idea: If we treat our local Web page as an object, then we can modify in response to data sent back by the server

  44. Lecture 3: AJAX and DOM • For example, consider the methods /attributes for accessing/modifying data in an HTML table: • First we need to get the table itself • If we assign it an "id" attribute, we can use the method getElementById() • We may then want a particular row • We can use the rows[] array • We may then want a specific cell • We can use the cells[] array from the row • And we may want to modify that cell • We can use the innerHTML attribute • Not true DOM – see handout for another way • See CDpoll.php and tabulate.php

  45. Lecture 3: AJAX and DOM • However, what if we want to make more significant changes? • Ex: Add a new row to a table • Get the table again • Insert a new row • Use insertRow() • Insert a new cell • Use insertCell() • Add the data to the cell • Use createTextNode() for text • More complex for the radio button – see handout • Use appendChild()

  46. Lecture 4: AJAX and DOM • Caution: • Be aware that AJAX can update data locally and can cause inconsistency with data at server • 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

  47. Lecture 4: AJAX and DOM • 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

  48. Lecture 4: Updating the Page • One way to keep a page updated is to have it automatically connect to a server for new information • We can do this with our CD poll so that even if the user does not enter a new CD, we will still see entries that other users have entered • This can be done in a fairly simple way utilizing: • AJAX requests • A Javascript timer

  49. Lecture 4: Updating the Page • When the page is loaded the timer starts • When it “goes off” an AJAX request is triggered to check with the server for any new CD entries • The timer is then reset for the next request • See CDpoll-update.php andtabulate-update.php • Note that we now have some consistency concerns to consider

  50. Lecture 4: Updating the Page • Consider the following scenario: • Timer goes off to update the page • Before the result is posted to the table, the user enters a new CD into the poll (generating another request) • In this situation, both requests will send back new rows for the table, and the table will be updated twice • Note that the DB will still be consistent • What is not consistent is the client • We can prevent this with some simple synchronization • See CDpoll-update.php

More Related