Client-Side Programming JavaScript & Ajax

3y ago
36 Views
4 Downloads
306.84 KB
9 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Ciara Libby
Transcription

CSE 135Client-Side ProgrammingJavaScript & AjaxFrom pure server to client/servercomputation So far we have seen pure server-sideprogrammingNext Enrich user experience, interactivity with clientside computations (JavaScript)– For example, validate that the user typed a number ina textbox Combine the best of both worlds with Ajaxtechnologies– Assignment focus: live views2Architecturally speaking:Pure server-side programmingPure server-side architectureBrowserCurrentNew pagePageForm submissionleads to requestServer respondswith new, typicallyHTML pageServer31

Architecturally speaking:Client-side programming w JavascriptBrowserCurrent PageJavascriptcodeUser events may lead to activation ofJavascript code, evaluated by the browser.They lead either to alerts, prompts, etc orto modification of part () of the pageServer4Architecturally speaking:Ajax programming (@10 miles high)BrowserCurrent PageJavascriptrequest-producing codeJavascript responsehandling code updatesServer responds with data that areenough for the page update ()Event leads toJavascript activation,leading tohttp requestServer5Preview: From basics to higher-levelprogramming1. First examples will demonstrate the essentials:– Directly accessing and manipulating the DOM objectrepresentation of the data shown on the browser– Packing & unpacking response data via XML– Not part of assignment – just broad knowledge2. Making Javascript/DOM programming easierwith utilities– Transferring data via JSON– Jquery3. (much later) High level frameworks where youcan altogether avoid Javascript–––FORWARDRuby-on-Rails partialsGWT62

JavaScript Programming language embedded in HTML– Directly or indirectly Evaluated by the browser, interpreted Triggered on page load and on certainprogrammer-defined events While OO, it allows weak typing and manyoddities– Great opportunities for making a coding mess7JavaScript Example 1 html body script type "text/javascript” document.write("Hello World!"); /script /body /html DOM object,standing for entirety of displayed HTML8JavaScript Example 2 html head script type "text/javascript" function displayMessage() { alert("Hello!"); } /script /head body form input type "button" value "Click me!”onclick "displayMessage()" / /form /body /html 93

Basics Incorporate code in script element Code in body part evaluates on page load Code in head part are typically functionswaiting for events triggered by the user’sactivity on the browser Typical control structures– Statements, conditionals, loops, functions. Typical expressions JavaScript can access and modify the HTMLdocument and its parts (HTML elements)currently displayed10Specific available objects Predefined JavaScript objects:–––––Window: Represents a browser windowNavigator: Contains browser infoScreen: Contains client screen infoHistory: Visited URLs within a browser window (tricky)Location: Info about the current URL The displayed HTML’s DOM tree–––––Document: Top of navigationArea: Areas you may have defined inside mapsFormOption 11JavaScript Example 3 html body script type "text/javascript” // Write "Good Evening” if time 16 and 21var d new Date();var time d.getHours();if (time 21 && time 16)document.write(" b Good Evening /b ");elsedocument.write(" b Hello /b "); /script /body /html 124

Interaction Basics: Popup Boxes Alerts– Make sure the user saw something Confirmations– Click either "OK" or "Cancel" to proceed Prompts13JavaScript Example 4 html body script type "text/javascript" response confirm("If you proceed we’ll charge your card");document.write(response); /script /body /html 14JavaScript Example 5 html body script type "text/javascript" response prompt(“The page will be whatever you type here","default");document.write(response); /script /body /html 155

Events Elements of a page have associated events– Mouse click on a button– Mouse over the element’s area– Start typing in (selecting) an input box Trigger function upon event16JavaScript Example 6 html head script type "text/javascript" function displayMsg() { alert("This is Mars!"); } /script /head body img src "earth.jpg" br / img onmouseover "displayMsg()" src "mars.jpg" /body /html 17When Should You Use JavaScript? Client-side form validation– Avoid roundtrips to the server for simple validationcases Form dependencies– Particular forms become irrelevant in light of answerstyped in other forms Fancy stuff popping up– But avoid hiding important information in various formsof popups Client side computing of cookie-related niceties– We’ll see along with HTML5 Browser environment issues186

Invoke Function Upon Event – Example 8 head script type "text/javascript"src "javascript/example08.js" /script /head body form action "nowhere" onsubmit "return validate()" Name (max 10 characters): input type "text" id "fname" name "fname" size "20” Age (from 1 to 100): input type "text" id "age" name "age" size "20” E-mail: input type "text" id "email" name "email" size "20” input type "submit" value "Submit" /form /body In Ajax, we will get rid of the form element.We’ll just have a button element19 and Validate Values – Example 8function validate() {var at );var age document.getElementById("age").value;var fname document.getElementById("fname").value;var submitOK "true";if (fname.length 10){ alert("The name may have no more than 10 characters");submitOK "false"; }if (isNaN(age) age 1 age 100){ alert("The age must be a number between 1 and 100");submitOK "false”; }if (at -1){ alert("Not a valid e-mail!");submitOK "false"; }if (submitOK "false") { return false; }}20How To Access? Navigation from the top Search for elements using any of multiplepossible ways Access by ID – my prefered technique, definitelyso when jquery is not used– But be disciplined about creating IDs Typically associate HTML elements that will bemodified by JavaScript with IDs– You can use a span element if you want to associatean area with an ID217

Dependencies – Example 9 body Questionaire: form Gender: select id "gender" onchange "enableDisable()" option Female /option option Male /option /select Are you pregnant? select id "pregnant" option No /option option Yes /option /select /form /body 22Dependencies – Example 9 (cont’d) script type "text/javascript" function enableDisable() {if (document.getElementById("gender").selectedIndex 1)document.getElementById("pregnant").disabled ed false} /script 23JavaScript Example 10 (dismiss, wewill do the same with HTML5, cleaner) head script type "text/javascript" function getCookie(c name) {if (document.cookie.length 0) {c start document.cookie.indexOf(c name " ");if (c start ! -1) {c start c start c name.length 1;c end document.cookie.indexOf(";",c start);if (c end -1) c end document.cookie.lengthreturn unescape(document.cookie.substring(c start,c end));}}return "”}248

JavaScript Example 10 (cont’d)function setCookie(c name, value, expdays) {var exp new Date();exp.setDate(exp.getDate() expdays);document.cookie c name " " escape(value) ((expdays null) ? "" : "; expires " exp.toGMTString());}function checkCookie() {username getCookie('username');if (username ! null && username ! "")alert('Welcome again ' username '!');else {username prompt('Please enter your name:',"");if (username ! null && username! "")setCookie('username', username, 365);}}25JavaScript Example 10 (cont’d) /script /head body onLoad "checkCookie()" My page . /body 269

Javascript activation, leading to http request Javascript request-producing code Server responds with data that are enough for the page update ( ) Javascript response-handling code updates 6 Preview: From basics to higher-level programming 1. First examples will demonstrate the essentials:

Related Documents:

JavaScript Manual for LCCS Teachers 13 Client-side JavaScript vs. server-side JavaScript For many years JavaScript was a client-side scripting language. This was because JavaScript programs could only be run from inside web browsers which were installed on client machines. Because of the fact that JavaScript code can run on client devices it means

Introduction to AJAX Pat Morin COMP 2405. 2 Outline What is AJAX? - History - Uses - Pros and Cons An XML HTTP Transaction - Creating an XMLHTTPRequest . In an AJAX application, the JavaScript code then communicates with the server behind the scenes. 5 An AJAX Application (Cont'd)

- The Spark web app framework . Yahoo JavaScript PHP Amazon.com JavaScript Java, C , Perl Wikipedia.org JavaScript PHP, Hack Twitter.com JavaScript C , Java, Scala, Ruby Bing JavaScript ASP.net eBay.com JavaScript Java, JavaScript, Scala . Note the MVC architecture

JavaScript. Check a framework's documentation for details. Using the SDK with Web Browsers All major web browsers support execution of JavaScript. JavaScript code that is running in a web browser is often called client-side JavaScript. Using the SDK for JavaScript in a web browser differs from the way in which you use it for Node.js. The

Praise for Effective JavaScript "Living up to the expectation of an Effective Software Development Series pro-gramming book, Effective JavaScript by Dave Herman is a must-read for anyone who wants to do serious JavaScript programming. The book provides detailed explanations of the inner workings of JavaScript, which helps readers take better

Mastering Ajax, Part 6: Build DOM-based Web applications Mix the DOM and JavaScript -- those perfect Ajax companions-- to change a Web page's user interface without page reloads Skill Level: Intermediate Brett McLaughlin Author and Editor O'Reilly Media Inc. 12 Sep 2006 Combine the Document Object Model (DOM) with JavaScript code to create .

JavaScript directly within the HTML file. We can also include more than one script tag and can include a mix of internal JavaScript and external JavaScript files. This will be useful, for example, if we have some JavaScript that is appropriate for many of our webpages and then some JavaScript that is specific to one page. Function Definition

mathematics at an advanced level, including articulation to university degree study. The Unit will provide learners with opportunities to develop the knowledge, understanding and skills to apply a range of differential and integral calculus techniques to the solution of mathematical problems. Outcomes On successful completion of the Unit the learner will be able to: 1 Use differentiation .