1 / 56

Ajax, JavaScript and PHP

The Web Browser Environment. To understand client-side JavaScript, you must understand the programming environment provided by a web browser.Three important features of that programming environment:The Window object that serves as the global object and global execution context for the client-side

argyle
Download Presentation

Ajax, JavaScript and PHP

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. Ajax, JavaScript and PHP Browser, Window objects

    2. The Web Browser Environment To understand client-side JavaScript, you must understand the programming environment provided by a web browser. Three important features of that programming environment: The Window object that serves as the global object and global execution context for the client-side JavaScript code The client-side object hierarchy and the Document Object Model that forms a part of it The event-driven programming model

    3. The Window as Global Execution Context Window object represents the browser window (or frame) that displays the document. The Window object is the global object in client-side programming The window object defines a number of properties and methods that allow you to manipulate the web browser window. It also defines the document property for the Document object. It has two self-referential properties, window and self. You can use either global variable to refer directly to the Window object. Since the Window object is the global object in client-side JavaScript, all global variables are defined as properties of the window. The following 2 lines of code are the same: var answer = 42; // declare and initialize a global variable window.answer = 42; // create a new property of the Window obj

    4. The Client-Side Object Hierarchy and the DOM The Window object is the key object in client-side JavaScript. All other client-side objects are accessed via this object. (document property; location property, etc…) The Document object (and other client-side JavaScript objects) also have properties that refer to other objects. (Document object has a forms[ ] array containing Form objects) To refer to one of these forms: window. document.forms[0] To continue with the example: window.document.forms[0].elements[3].options[2].text Many of the objects descend from the Document object. This subtree of the larger client-side object hierarchy is known as the document object model (DOM).

    5. The Event-Driven Programming Model In client-side JavaScript, the web browser notifies programs of user input by generating events. (e.g. keystroke events, mouse motion events, etc…) When an event occurs, the web browser attempts to invoke an appropriate event handler function to respond to the event.

    6. The Role of JavaScript on the Web Web browsers display HTML-structured text styled with CSS stylesheets. HTML defines the content, and CSS supplies the presentation. Properly used, JavaScript adds behavior to the content and its presentation. The role of JavaScript is to enhance a user’s browsing experience, making it easier to obtain or transmit information.

    7. Embedding Scripts in HTML Client-Side JavaScript code is embedded within HTML documents in a number of ways: Between a pair of <script> and </script> tags From an external file specified by the src attribute of a <script> tag In an event handler, specified as the value of an HTML attribute such as onclick or onmousover In a URL that uses the special javascript: protocol

    8. The <script> Tag Client-side JavaScript scripts are part of an HTML file and are coded within <script> and </script> tags: <script> // your JavaScript code goes here </script> A simple JavaScript program in an HTML file: <html> <head><title>Today’s date</title> <script language=“JavaScript” type=“text/javascript”> function print_todays_date() { var d = new Date(); document.write(d.toLocaleString()); } </script> </head> <body> The date and time are:<br> <script language=“JavaScript” type=“text/javascript”> print_todays_date(); </script> </body> </html>

    9. Scripts in External Files The <script> tag supports a src attribute that specifies the URL of a file containing JavaScript code: <script src=“util.js”> </script> A JavaScript file typically has a .js extension and contains pure JavaScript, without <script> tags or any other HTML.

    10. Specifying the Scripting Language There are two scripting language for the Web. JavaScript and Microsoft’s Visual Basic Scripting Edition (supported by Internet Explorer) You can specify the default scripting language for a file with the HTTP Content-Script-Type header, and you can simulate this header with the HTML <meta> tag. <meta http-equiv=“Content-Type” content=“text/javascript”> In practice, browsers assume that JavaScript is the default scripting language even if your server omits the Content-Script-Type header. If you wish to override your default, you should use the type attribute of the <script> tag: <script type=“text/javascript”> // js code </script>

    11. Specifying the Scripting Language JavaScript programs are not really text documents, it marks this type as obsolete and recommends “application/javascript” instead. However, “application/javascript” is not well supported, once it has become well supported, the most appropriate <script> and <meta> tags will be: <script type=“application/javascript”> </script> <meta http-equiv=“Content-Script-Type” content=“application/javascript”> When the <script> tag was first introduced, it was not support the type attribute. It was defined with the language attribute. <script language=“JavaScript”> // JS code </script>

    12. Specifying the Scripting Language The HTML 4 specification standardized the <script> tag, but it deprecated the language attribute . Sometimes you will see <script> tags that use the type attribute for standards compliance and the language attribute for backward compatibility with older browsers: The language attribute is sometimes used to specify the version of JavaScript in which a script is written: <script language=“JavaScript1.2”> </script> <script language=“JavaScript1.5”> </script> Note: an old browser that does not support JavaScript 1.5 will not attempt to run a script that has a language attribute of “JavaScript1.5”.

    13. The <noscript> Tag HTML defines the <noscript> element to hold content that should be rendered only if JavaScript has been disabled in the browser. You can use <noscript> to notify the users that JavaScript is required and possibly to provide a link to alternative content. <body> ... <script type="text/javascript"> <!-- document.write("Hello World!") //--> </script> <noscript>Your browser does not support JavaScript!</noscript> ... </body>

    14. Hiding Scripts from Old Browsers When JavaScript was new, some browsers did not recognize the <script> tag and would render the content of this tag as text. The workaround is to use HTML comments inside the script tag. <script language=“JavaScript”> <!-- Begin HTML comment that hide the script // js statements // more js statements // end html comments that hide the script --> </script> Or, more compactly: <script> <!-- // js statements //--></script>

    15. Event Handlers in HTML More dynamic programs define event handlers that are automatically invoked by the web browser when certain events occur. Because events in client-side JavaScript originate from HTML objects (such as buttons), event handlers can be defined as attributes of those objects: <input type=“checkbox” name=“options” value=“giftwrap” onclick=“giftwrap();”> These are the most common event handlers: onclick onmousedown, onmouseup onmouseover, onmouseout onchange onload

    16. JavaScript in URLs Another way that JavaScript code can be included on the client side is in a URL following the javascript: pseudo protocol specifier. This string of JavaScript code is treated as a single line of code, which means that statements must be separated by semicolons and that /* */ comments must be used in place of // comments: javascript: var now = new Date(); “<h1>The time is:</h1>” + now; The browser executes the JavaScript code contained in the URL and uses the value of the last JavaScript statement or expression, converted to a string, as the contents of the new document to display. This string value may contain HTML tags and is formatted and displayed just like any other document loaded into the browser. JavaScript URLs may also contain JavaScript statements that perform actions but return no value: javascript:alert(“Hello World!”)

    17. JavaScript in URLs To use a JavaScript URL to execute some JavaScript code without altering the currently displayed document, be sure that the last statement in the URL has no return value. Or use the void operator to explicitly specify an undefined return value: javascript:window.open(“about:blank”); void o; You can use a JavaScript URL anywhere you would use a regular URL. One handy way to use this syntax is to type it directly into the location field of your browser, where you can test arbitrary JavaScript code without having to open your editor and create an HTML file containing the code.

    18. Execution of JavaScript Programs The JavaScript code in <script> tags is executed as part of document loading and parsing process. Document loading process: Load document (execute <script>) Parse document (text output from <script> will be displayed in document) Load image, sound, etc… Execute onload event (browser fires off this event) JavaScript Event-driven phase and JavaScript URLs (mouse motion, mouse click, key press, etc…) Execute onunload event Note: when the onload handler is triggered, the document is fully loaded and parsed. Therefore, onload event handler must not call document.write(). It will overwrite the current document.

    19. Window & Document Objects

    20. Window Object (Global Object) Window Properties Document: document object Location: location object History: history object (array). history.back(), history.forward(), history.go() Navigator: navigator object (Browser information) Self: Refers to the current window. Equivalent to window Opener: Refers to the window from which a particular window was opened

    21. Window Object (Global Object) Window Methods alert() back() blur() clearInterval() clearTimeout() close() confirm() focus()

    22. Window Object (Global Object) forward() home() open() print() prompt() setInterval() setTimeout() stop()

    23. Document object Document object collection: images[] forms[] elements[] (button, checkbox, hidden, password, radio, reset, select, submit, text, textarea) links[] anchors[] Document object properties: lastModified title URL

    24. Document object Document object methods close() getElementById() getElementsByName() getElementsByTagname() open() write() writeln()

    25. Timers The core JavaScript language does not provide ability to schedule code to be executed at some point in the future, but client-side JavaScript does provide it in the form of the global functions setTimeout(), clearTimeout(), setInterval(), and clearInterval(). The setTimeout() method of the Window object schedules a function to run after a specified number of miliseconds elapses. It returns an opaque value that can be passed to clearTimeout() to cancel the execution of the scheduled function. The setInterval() invokes the specified function repeatedly at intervals of the specified number of miliseconds. It returns an opaque value that can be passed to clearInterval() to cancel any future invocations of the scheduled function.

    26. Browser Location and History The location property of a window (or frame) is a reference to a Location object; it represents the URL of the document currently being displayed in that window. The href property of the Location object is a string that contains the complete text of the URL. The toString() method of the Location object returns the value of the href property, so you can use location in place of location.href: location.href location.toString() /* this 2 statements are the same */

    27. Loading New Documents Although the location property of a window refers to a Location object, you can assign a string value to the property. When you do this, the browser interprets the string as a URL and attempt to load and display the document at the URL: /* if the browser does not support the Document.getElementById function, redirect to a static page. */ if (!document.getElementById) location = “staticpage.html”; Historically, assigning a URL to the location property of a window has been the supported technique for loading new pages.

    28. Loading New Documents The Location object have two objects with related purposes: The reload() method reloads the currently displayed page from the web server; The replace() method loads and displays a URL that you specify. When you call this method, the specified URL replaces the current one in the browser’s history list rather than creating a new entry in that history list. Therefore, the Back button does not take the user back to the original document. Finally, the location property of the Window object refers to a Location object. The location property of the Document object is simply a read-only string. document.location is a synonym for document.URL In most cases, document.location is the same as location.href. When there is a server redirect, however, document.location contains the URL as loaded, and location.href contains the URL as originally requested.

    29. The History Object The history property of the Window object refers to the History object for the window. For security and privacy reasons, the array elements of the History object are never actually accessible to scripts. Although its array elements are inaccessible, the History object supports three methods: The back() and forward() methods move backward or forward in a window’s (or frame’s) browsing history, replacing the currently displayed document with a previously viewed one. The go() method, takes an integer argument and can skip any number of pages forward (for positive arguments) or backward (for negative arguments) in the history list. history.back() history.forward() history.go(+2) history.go(-3)

    30. Obtaining Window, Screen, and Browser Information The navigator property of a Window object refers to a Navigator object that contains information about the web browser as a whole. In the past, the Navigator object was commonly used by scripts to determine if they were running in Internet Explorer or Netscape. This browser-sniffing approach is replaced by a capability-testing approach: if (window.addEventListener) { // addEventListener() method supports by Netscape/Mozilla/Firefox } else if (window.attachEvent) { // attachEvent() method supports by IE } else { // old browsers }

    31. The Navigator Object Browser sniffing is sometimes still valuable, however, one such case is when you need to work around a specific bug that exists in a specific version of a specific browser. The Navigator object lets you do this. The Navigator object has five properties that provide version information about the browser that is running: appName; appVersion; userAgent; appCodeName; platform. The following lines of JavaScript code display each Navigator object property in a dialog box: var browser = “BROWSER INFORMATION: \n”; for (var propname in navigator) { browser += propname + “: “ + navigator[propname] + “\n” } alert(browser);

    32. The Navigator Object Client sniffer (http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html) /* this module defines an object named “browser” that is easier to use than the “navigator” object */ var browser = { version: parseInt(navigator.appVersion), isNetscape: navigator.appName.indexOf(“Netscape”) != -1, isMicrosoft: navigator.appName.indexOf(“Microsoft”) != -1 }; This is one of the reasons that browser sniffing has become less useful and is being superseded by capability testing.

    33. Opening and Manipulating Windows The Window object defines several methods allow you to open and close windows, control window position and size, request and relinquish keyboard focus, and scroll the contents of a window.

    34. Opening Windows You can open a new web browser window with the open() method of the Window object. window.open() takes four optional arguments and returns a Window object that represents the newly opened window: window.oprn(“URL”, “winname”, “featureslist”, booleanvalue); URL: URL of the document to display in the new window. If omitted or null or empty string, the window will be empty Winname: the name of the window Featureslist: list of features that specify the window size and GUI decorations. Booleanvalue: specifies whether the URL specified as the first argument should replace the current entry in the window’s browsing history (true) or create a new entry in the window’s browsing history (false), which is the default behavior var w = window.open(“smallwin.html”, “smallwin”, “width=400,height=350,status=yes,resizable=yes”); The return value of the open() method is the Window object that represents the newly created window. The opener property of a window refers to the window from which it was opened. If the window was created by the user, the opener property is null.

    35. Closing Windows The close() method closes the current window. If you create a Window object w, you can close it with: w.close(); JavaScript code running within that window itself can close it with: window.close(); Note: the explicit use of the window identifier to distinguish the close() method of the Window object from the close() method of the Document object (document.close( )).

    36. Keyboard Focus and Visibility Calling focus( ) requests that the system give keyboard focus to the window Calling blur( ) relinquishes keyboard focus Note: the focus( ) method ensures that the window is visible by moving it to the top of the stacking order.

    37. Simple Dialog Boxes The Window object provides three methods for displaying simple dialog boxes to the user. alert( ) displays a message to the user and waits for the user to dismiss the dialog (use for degugging) confirm( ) asks the user to click an OK or Cancel button to confirm or cacnel an operation prompt( ) asks the user to enter a string

    38. Scripting the Status Line Web browser typically display a status line at the bottom of every window in which the browser can display message to the user. In old browser, you can set the status property to specify text that the browser should temporarily display in the status line: confused? Try the <a href=“help.html” onmouseover = “status=‘Click here for help!’; return true;”>Online Help</a> Modern browsers have disabled the ability to set the status property.

    39. Scripting the Status Line The Window object also defines a defaultStatus property that specifies text to be displayed in the status line when the browser doesn’t have anything else to display there. (defaultStatus works in some browsers but not all): <script> var WastedTime = { start: new Date(), displayElapsedTime: function() { var now = new Date(); var elapsed = Math.round((now – WastedTime.start)/60000); window.defaultStatus = “You have wasted “ + elapsed + “ minutes. “; } } // update the status line every minute setInterval(WastedTime.displayElapsedTime, 60000); </script>

    40. Error handling The onerror property of a Window object is special. If you assign a function to this property, the function is invoked whenever a JavaScript error occurs in that window: the function you assign becomes an error handler for the window. Three arguments are passed to an error handler when a JavaScript error occurs: The first argument is a message describing the error The second argument is a string that contains the URL of the document containing the JavaScript code that caused the error The third argument is the line number within the document where the error occurred If the onerror handler returns true, it tells the browser that the handler has handled the error and that no further action is necessary.

    41. Error Handling Define an error handler that handles all errors silently: // don’t bother the user with error messages window.onerror = function() { return true; } Display error messages not more than 3 times: window.onerror = function(msg, url, line) { if (onerror.num++ < onerror.max) { alert(“ERROR: “ + msg + “\n” + url + “:” + line); } } onerror.max = 3; onerror.num = 0;

    42. Window Synonyms

    43. Opening and Closing a Pop-up Window <html> <head><title>Open and close pop-up window</title> <script language="JavaScript"> <!-- var map = null; function showMap() { var features = "width=620, height=650"; features += ", left=50, top=50,status"; map = window.open("map.html", "MapWin", features); map.focus(); } function closeMap() { if (map != null) { map.close(); map = null; } } //--> </script> </head> <body> <h1>Contact us (CCSF)</h1> <p>50 Phelan Avenue<br/> San Francisco, CA 94112<br/> (415) 239-3000</p> <p><a href="javascript: void(0)" onclick="showMap()">View Map</a> | <a href="http://www.ccsf.edu/Offices/Office_of_Instruction/Access_Guide/" target="MapWin">View Driving Directions</a> | <a href="javascript: void(0)" onclick = "closeMap()">Close Map</a></p> </body> </html>

    44. Map.html <html> <head><title>Map file</title> </head> <body> <div align="center"> <h2>Map to CCSF</h2> <img src="ccsf_map.bmp" border="0" alt="CCSF_MAP" width="400" height="400"> <form> <input type="button" value="Print" onclick="window.print()"> <input type="button" value="Return" onclick="opener.focus()"> <input type="button" value="Close" onclick="self.close()"> </form> </div> </body> </html>

    45. Pop-up News <html> <head><title>Popup News</title> <script language="JavaScript"> <!-- function showNews() { news = window.open("http://www.cnn.com", "NewsWin", "width=200, height=220"); newsTimer = setTimeout("news.close()", "20000"); } //--> </script> </head> <body onload="showNews()"> <h2>Popup News</h2> </body> </html>

    46. Targeting Windows

    47. Targeting Windows <html> <head><title>Window target</title> </head> <body> <a href=“somepage.html” target=“???”>Some page</a> </body> </html>

    48. Opening a pop-up Window [windowObjectName=] [window.] open(“URL”, “targetName” [, “features”]) windowObjectName: specifies the name of the window object variable. It is used to call methods on the window and access the window properties. URL: specifies the URL of the file to open in the new window. If you want to write to the new window dynamically, do not specify a URL, just provide empty quotes (“”). targetName: name to be used in the target attribute of an <a> tag. It can only be alphanumeric or underscore. features: comma-separated list (without spaces) of any of the following options and values.

    49. Opening a pop-up window

    50. Opening a pop-up window

    51. Opening a pop-up window

    52. Closing a window Call the close method with the window’s name To close myMap: myMap.close();

    53. Window methods

    54. Window methods

    55. Window methods

    56. Window methods

    57. Writing to windows dynamically <html> <head><title>dynamic window text</title> <script language="JavaScript" type="text/javascript"> <!-- function dynWrite() { var topDoc = "<html><head><title>Dynamic text</title></head>"; topDoc += "<body bgcolor='yellow' text='black'>"; var endDoc = "</body></html>"; var features = "width='200',height='200'"; var newWin = window.open("", "DynWin", features); newWin.document.write(topDoc, "<h2>Dynamically write text</h2>"); newWin.document.write("Quote of the day: Please turn in your homework. Thanks."); newWin.document.write("<div align='center'>", "<input type='button' value='close' onClick='self.close()'></div>"); newWin.document.write(endDoc); } //--> </script> </head> <body onLoad="dynWrite()"> <h1>Home page of some web site</h1> </body> </html>

More Related