JavaScript 4 JavaScript 4 Objects and JSON Dr Kevin McManus with material borrowed from Gill Windall

Slides:



Advertisements
Similar presentations
Chapter 7 JavaScript: Introduction to Scripting. Outline Simple Programs Objects and Variables Obtaining User Input with prompt Dialogs – –Dynamic Welcome.
Advertisements

CG0119 Web Database Systems Parsing XML: using SimpleXML & XSLT.
JavaScript and AJAX Jonathan Foss University of Warwick
JavaScript FaaDoOEngineers.com FaaDoOEngineers.com.
The Web Warrior Guide to Web Design Technologies
Cloud Computing Lecture #7 Introduction to Ajax Jimmy Lin The iSchool University of Maryland Wednesday, October 15, 2008 This work is licensed under a.
Chapter 11 ASP.NET JavaScript, Third Edition. 2 Objectives Learn about client/server architecture Study server-side scripting Create ASP.NET applications.
15-Jul-15 JSON. JSON example “JSON” stands for “JavaScript Object Notation” Despite the name, JSON is a (mostly) language-independent way of specifying.
JavaScript Demo Presented by … Jaisingh Sumit jain Sudhindra Taran Deep arora.
CST JavaScript Validating Form Data with JavaScript.
JSON (JavaScript Object Notation).  A lightweight data-interchange format  A subset of the object literal notation of JavaScript (or ECMA-262).  A.
August Chapter 1 - Essential PHP spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
The Document Object Model (DOM) & Asynchronous Javascript And XML (AJAX) : an introduction UFCEKG-20-2 : Data, Schemas and Applications.
Introduction to PHP and Server Side Technology. Slide 2 PHP History Created in 1995 PHP 5.0 is the current version It’s been around since 2004.
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
Chapter 5 Java Script And Forms JavaScript, Third Edition.
CSCI 6962: Server-side Design and Programming Introduction to AJAX.
Lecture 12 – AJAX SFDV3011 – Advanced Web Development Reference: 1.
Introduction to JavaScript 11 Introduction to Programming the WWW I CMSC Winter 2004 Lecture 14.
Overview of Previous Lesson(s) Over View  ASP.NET Pages  Modular in nature and divided into the core sections  Page directives  Code Section  Page.
XML and its applications: 4. Processing XML using PHP.
The Document Object Model. Goals Understand how a JavaScript can communicate with the web page in which it “lives.” Understand how to use dot notation.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
Chapter 3 : Processing on the Front End JavaScript Technically its name is ECMA-262, which refers to the international standard which defines it. The standard.
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
Client side web programming Introduction Jaana Holvikivi, DSc. School of ICT.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
CIS 451: ASP.NET Objects Dr. Ralph D. Westfall January, 2009.
Using Client-Side Scripts to Enhance Web Applications 1.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Introduction to JavaScript 41 Introduction to Programming the WWW I CMSC Winter 2004 Lecture 17.
Lecture 9: AJAX, Javascript review..  AJAX  Synchronous vs. asynchronous browsing.  Refreshing only “part of a page” from a URL.  Frameworks: Prototype,
Ajax. –Asynchronous JavaScript and XML –Umbrella term for technologies that often: Use client-side scripting for layout and formatting Use less than full.
Server-side Programming The combination of –HTML –JavaScript –DOM is sometimes referred to as Dynamic HTML (DHTML) Web pages that include scripting are.
Asynchronous Javascript And XML AJAX : an introduction UFCEUS-20-2 : Web Programming.
Chapter 16: Ajax-Enabled Rich Internet Applications with XML and JSON TP2543 Web Programming Mohammad Faidzul Nasrudin.
4. Javascript M. Udin Harun Al Rasyid, S.Kom, Ph.D Lab Jaringan Komputer (C-307) Desain.
 Previous lessons have focused on client-side scripts  Programs embedded in the page’s HTML code  Can also execute scripts on the server  Server-side.
©SoftMooreSlide 1 Introduction to HTML: Forms ©SoftMooreSlide 2 Forms Forms provide a simple mechanism for collecting user data and submitting it to.
 Web pages originally static  Page is delivered exactly as stored on server  Same information displayed for all users, from all contexts  Dynamic.
AJAX. Ajax  $.get  $.post  $.getJSON  $.ajax  json and xml  Looping over data results, success and error callbacks.
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
CHAPTER 8 AJAX & JSON WHAT IS AJAX? Ajax lets you…
AJAX and REST. Slide 2 What is AJAX? It’s an acronym for Asynchronous JavaScript and XML Although requests need not be asynchronous It’s not really a.
OVERVIEW AND PARSING JSON. What is JSON JavaScript Object Notation Used to format data Commonly used in Web as a vehicle to describe data being sent between.
AJAX CS456 Fall Examples Where is AJAX used? Why do we care?
Jackson, Web Technologies: A Computer Science Perspective, © 2007 Prentice-Hall, Inc. All rights reserved Chapter 7 Representing Web Data:
Javascript Basic Concepts Presentation By: Er. Sunny Chanday Lecturer CSE/IT RBIENT.
JavaScript and Ajax (JavaScript Environment) Week 6 Web site:
Javascript AJAX HTML WEB SERVER Asynchronous. Javascript HTML events DOM – document object model browser internal view of html page compute.
1 Objects In JavaScript. 2 Types of Object in JavaScript Built-in objects User Defined Objects Browser Object Document Object Model.
JSON (Copied from and from Prof Da Silva) Week 12 Web site:
JavaScript and Ajax Week 10 Web site:
XML & JSON. Background XML and JSON are to standard, textual data formats for representing arbitrary data – XML stands for “eXtensible Markup Language”
JQuery, JSON, AJAX. AJAX: Async JavaScript & XML In traditional Web coding, to get information from a database or a file on the server –make an HTML form.
11 jQuery Web Service Client. 22 Objectives You will be able to Use JSON (JavaScript Object Notation) for communcations between browser and server methods.
//liveVirtualacademy2011/ What’s New for ASP.NET 4.5 and Web Development in Visual Studio 11 Developer Preview Γιώργος Καπνιάς MVP, MCT, MCDP, MCDBA, MCTS,
Build in Objects In JavaScript, almost "everything" is an object.
Unit 4 Representing Web Data: XML
Scope, Objects, Strings, Numbers
AJAX.
14 A Brief Look at JavaScript and jQuery.
Web Systems Development (CSC-215)
ISC440: Web Programming 2 AJAX
MIS JavaScript and API Workshop (Part 3)
Introduction to AJAX and JSON
Ajax and JSON Jeremy Shafer Department of MIS Fox School of Business
Ajax and JSON Jeremy Shafer Department of MIS Fox School of Business
PHP and JSON Topics Review JSON.
Presentation transcript:

JavaScript 4 JavaScript 4 Objects and JSON Dr Kevin McManus with material borrowed from Gill Windall

JavaScript 4 © 2015the University of Greenwich 2 Introduction JavaScript is not a truly Object Oriented language unlike Smalltalk, C++ or Java JavaScript is an Object Based language in JavaScript almost everything is an object all primitive types except null and undefined are treated as objects Since XML based web services became pervasive and enabled development of 4 th generation Web 2.0 applications, JavaScript Object Notation (JSON) popularity has increased as an alternative to XML, especially for AJAX approaches to Web application development why? what are the relative merits of JSON and XML?

JavaScript 4 © 2015the University of Greenwich 3 Types of JavaScript Objects We have seen that JavaScript objects can be classified into three types object types built into the core language e.g. Object, Array, String, Date, Math, RegExp client-side (or server-side) objects for interacting with the browser and document (or server-side environment) e.g. document, history, window, navigator programmer defined object types the focus of this lecture

JavaScript 4 © 2015the University of Greenwich 4 Creating JavaScript Object Types In this example objects are used to represent a single line from an order Each orderLine object has: three properties product unitPrice number two methods calcCost – unit price times number displayLine - to output HTML representing the order line

JavaScript 4 © 2015the University of Greenwich 5 General Purpose Object In JavaScript you can instance a general purpose object an associative array of values - properties property value could be a function – method var orderLine1 = new Object(); orderLine1.product = "pencils"; orderLine1.unitPrice = 0.45; orderLine1["number"] = 8; orderLine1.calcCost = calculateLineCost; associative array syntax this function must be previously defined

JavaScript 4 © 2015the University of Greenwich 6 General Purpose Object In this example calculateLineCost and displayOrderLine have previously been defined as functions function calculateLineCost() { return this.unitPrice * this.number; } function displayOrderLine() { document.getElementById("invoice").innerHTML += " " + this.product + " " + " " + this.unitPrice + " " + " " + this.number + " " + " " + this.calcCost() + " "; }

JavaScript 4 © 2015the University of Greenwich 7 General Purpose Object <!— function calculateLineCost() { return this.unitPrice * this.number; } function displayOrderLine() { document.getElementById("invoice").innerHTML += " " + this.product + " " + " " + this.unitPrice + " " + " " + this.number + " " + " " + this.calcCost() + " "; } generalPurposeObject.html start with the required functions

JavaScript 4 © 2015the University of Greenwich 8 var orderLine1 = new Object(); orderLine1.product = "pencils"; orderLine1.unitPrice = 0.45; orderLine1.number = 8; orderLine1.calcCost = calculateLineCost; orderLine1.writeLine = displayOrderLine; var orderLine2 = new Object(); orderLine2.product = "mugs"; orderLine2.unitPrice = 3.00; orderLine2.number = 3; orderLine2.calcCost = calculateLineCost; orderLine2.writeLine = displayOrderLine; function init() { orderLine1.writeLine(); orderLine2.writeLine(); } // --> Order Details product price number cost instance an object for pencils instance an object for mugs onload event calls init() data goes in this table

JavaScript 4 © 2015the University of Greenwich 9 Questions 1.What do you think would happen if this line orderLine2.unitPrice = 3.00; were mistyped as: orderLine2.unitprice = 3.00; 2.Do you think that JavaScript supports method overloading?

JavaScript 4 © 2015the University of Greenwich 10 Creating Custom Object Types An object type can easily be created by defining a constructor method function OrderLine(prod, price, numb) { this.product = prod; this.unitPrice = price; this.number = numb; this.calcCost = calculateLineCost; this.writeLine = displayOrderLine; } var orderLine1 = new OrderLine("pencils",0.45,8); orderLine1.writeLine(); objectConstructor.html method name and function name are often the same

JavaScript 4 © 2015the University of Greenwich 11 Prototypes In the previous two examples each instance of the object has its own copy of the properties and methods but the code for the calcCost and writeLine methods are the same for each instance of the type it is inefficient to store the code in each instance. The solution is to make use of the object's prototype every JavaScript object has a prototype

JavaScript 4 © 2015the University of Greenwich 12 Prototypes If you want all instances of an object type to share a property value or method then you assign it to the constructor's prototype function OrderLine(prod, price, numb) { this.product = prod; this.unitPrice = price; this.number = numb; } OrderLine.prototype.calcCost = calculateLineCost; OrderLine.prototype.writeLine = displayOrderLine; OrderLine.prototype.currency = "£"; character reference for £ runs when an OrderLine object is created runs once

JavaScript 4 © 2015the University of Greenwich 13 Prototypes Prototype currency : "£" calcCost() { return this.unitPrice * this.number; } writeLine() {... } orderLine1 product : "pencils" price : 0.45 number : 8 orderLine2 product : "mugs" price : 3.00 number : 3

JavaScript 4 © 2015the University of Greenwich 14 Prototypes When assigning a property for an object JavaScript doesn't check to see if it exists in the prototype if necessary the property will be created in the object var orderLine1 = new OrderLine("pencils",0.45,8); var orderLine2 = new OrderLine("mugs",3.00,3); orderLine2.currency = "$"; a currency property will be created in orderLine2 overrules the currency of the prototype

JavaScript 4 © 2015the University of Greenwich 15 objectPrototype.html OrderLine Prototype currency : "£" calcCost() { return this.unitPrice * this.number; } writeLine() {... } orderLine1 product : "pencils" unitPrice: 0.45 number : 8 orderLine2 product : "mugs" unitPrice: 3.00 number : 3 currency : "$"

JavaScript 4 © 2015the University of Greenwich 16 Inheritance Most OO languages have a mechanism where you can build hierarchies of object classes each class inherits properties and methods from it’s parent Account CurrentAccount DepositAccount CashAccountEquityAccount GrowthAccountIncomeAccount

JavaScript 4 © 2015the University of Greenwich 17 Inheritance function OrderLineDiscount(prod, price, numb, disc) { this.product = prod; this.unitPrice = price; this.number = numb; this.discount = disc; } OrderLineDiscount.prototype = new OrderLine("", 0, 0); OrderLineDiscount.prototype.calcCost = calculateLineCostWithDiscount; OrderLineDiscount inherits the currency property and calcCost and writeLine methods from OrderLine OrderLineDiscount constructor calcCost method is replaced in the OrderLineDiscount prototype OrderLine OrderLineDiscount

JavaScript 4 © 2015the University of Greenwich 18 objectInheritance.html OrderLineDiscount calcCost : calculateLineCostWithDiscount() OrderLine currency : "£" product unitPrice number calcCost() writeLine()

JavaScript 4 © 2015the University of Greenwich 19 objectInheritance.html from instance of OrderLineDiscount from instances of OrderLine

JavaScript 4 © 2015the University of Greenwich 20 JSON JavaScript Object Notation not just for use with JavaScript Text-based and human-readable Used to communicate data in the form of serialized objects an alternative to XML smaller and quicker to process

JavaScript 4 © 2015the University of Greenwich 21 JSON Syntax {"product":"pencils", "unitPrice":0.45, "number":8} fields separated by commas curly braces hold objects field names in quotes name:value pairs numeric values not quoted string values in quotes

JavaScript 4 © 2015the University of Greenwich 22 JSON Syntax { "firstName": "Betty", "lastName": "Rubble", "age": 28, "address": { "line1": "21 Main Street", "line2": "Bridport", "county": "Suffolk", "postCode": "BD23 3DG" }, "phoneNumber": [ { "type": "home", "number": " " }, { "type": "mobile", "number": " " } ] } objects array of two objects

JavaScript 4 © 2015the University of Greenwich 23 jsonObject.html var orderLine1 = { "product":"pencils", "unitPrice":0.45, "number":8 }; orderLine1.calcCost = calculateLineCost; orderLine1.writeLine = displayOrderLine; var orderLine2txt = '{"product":"mugs","unitPrice":3.00,"number":3}'; var orderLine2 = eval ("(" + orderLine2txt + ")"); orderLine2.calcCost = calculateLineCost; orderLine2.writeLine = displayOrderLine; This is much the same as the generic object example but demonstrates 2 ways of instantiating objects from JSON methods are added after using JSON to create objects with properties JSON notation eval a JSON format string

JavaScript 4 © 2015the University of Greenwich 24 Adding Methods JSON can only provide object properties Use JSON in an object constructor to provide methods for the JSON object function OrderLine(obj) { for (var prop in obj) this[prop] = obj[prop]; this.calcCost = calculateLineCost; this.writeLine = displayOrderLine; } JSON object array syntax

JavaScript 4 © 2015the University of Greenwich 25 jsonConstructor.html function OrderLine(obj) { for (var prop in obj) this[prop] = obj[prop]; this.calcCost = calculateLineCost; this.writeLine = displayOrderLine; } var jsonOrderLine1 = { "product":"pencils", "unitPrice":0.45, "number":8 }; var orderLine1 = new OrderLine(jsonOrderLine1); var jsonOrderLine2 = { "product":"mugs", "unitPrice":3.00, "number":3 }; var orderLine2 = new OrderLine(jsonOrderLine2); create two JSON objects constructor with methods use the JSON objects to instance two objects with methods

JavaScript 4 © 2015the University of Greenwich 26 JSON Services In the examples so far JSON has not been much use the main points about using JSON have been covered JSON is useful as a serialisation mechanism to transport objects web services

JavaScript 4 © 2015the University of Greenwich 27 jsonOrderLine1.php <?php $orderLine = array( 'product' => 'pencils', 'unitPrice' => 0.45, 'number' => 8 ); header('Content-Type: application/json' ); echo json_encode($orderLine); ?> PHP array ends up as a JSON string a more realistic example would obtain the order data from a database

JavaScript 4 © 2015the University of Greenwich 28 jsonPrototype.html Asynchronous (AJAX) loading of the JSON service does not guarantee item order

JavaScript 4 © 2015the University of Greenwich 29 jsonPrototype.html // OrderLine object constructor function OrderLine(obj) { for (var prop in obj) this[prop] = obj[prop]; this.calcCost = calculateLineCost; this.writeLine = displayOrderLine; } OrderLine.prototype.currency = "£"; OrderLine.prototype.calcCost = calculateLineCost; OrderLine.prototype.writeLine = displayOrderLine; // instance an XML HTTP request object var http = new XMLHttpRequest(); //no support for IE6 http.overrideMimeType("application/json"); http.onreadystatechange = handleJsonResponse; //assign callback function

JavaScript 4 © 2015the University of Greenwich 30 jsonPrototype.html // Event handler for the JSON response function handleJsonResponse() { if (http.readyState == 4) { var jsonOrderLine1 = eval ("(" + http.responseText + ")"); var orderLine1 = new OrderLine(jsonOrderLine1); orderLine1.writeLine("customerTable"); } // Send request asynchronusly function requestJSON(serviceURL) { http.open("GET",serviceURL,true); http.send(null); }

JavaScript 4 © 2015the University of Greenwich 31 jsonPrototype.html // instantiate order line 2 object var jsonOrderLine2 = { "product":"mugs", "unitPrice":3.00, "number":3 }; var orderLine2 = new OrderLine(jsonOrderLine2); orderLine2.currency = "$"; // write the objects into the page function init() { // asynchronously request and write order line 1 requestJSON("jsonOrderLine1.php"); // write order line 2 orderLine2.writeLine(); }

JavaScript 4 © 2015the University of Greenwich 32 XML to JSON <!ATTLIST price currency ( ukpound | egpound | usdollar | audollar | euro ) "ukpound" > fork candle This XML takes a slightly different approach to the data model

JavaScript 4 © 2015the University of Greenwich 33 jsonOrdersFromXML.php <?php // load an XML DOM object $url = 'orders.xml'; // this could be a web service $xmlDom = new DOMDocument(); $xmlDom->load($url,LIBXML_NOBLANKS); // convert it into a string - need not have bothered with the DOM $xmlString = $xmlDom->saveXML(); // load the string into a SimpleXML object - strips out the attributes $simpleXML = simplexml_load_string($xmlString); // encode the SimpleXML object as JSON and return it header('Content-Type: application/json'); echo json_encode($simpleXML); ?> JSON but not as we want it

JavaScript 4 © 2015the University of Greenwich 34 jsonOrderLinesFromXML.php <?php // read XML data into a DOM object $url = 'orders.xml'; // this could be a web service $xmlDom = new DOMDocument(); $xmlDom->load($url,LIBXML_NOBLANKS); // instantiate an XSLT processor and import XSL file into it $xslt = new XSLTProcessor(); $xslDom = new DOMDocument(); $xslDom->load('orderLines.xsl', LIBXML_NOCDATA); $xslt->importStylesheet($xslDom); // return the transformed XML header('Content-Type: application/json'); echo $xslt->transformToXML($xmlDom); ?> JSON in a more appropriate format

JavaScript 4 © 2015the University of Greenwich 35 orderLines.xsl {"orderLine":[ { "product":" ", "unitPrice":, "currency":" ", "number": }, ]} comma delimiter XML attribute becomes a JSON property XML element names translated to JSON property names

JavaScript 4 © 2015the University of Greenwich 36 jsonPrototype4.html orderLine from literal JSON orderLines from JSON web service translating XML orderLine from JSON web service this example takes a slightly different approach to handling currency

JavaScript 4 © 2015the University of Greenwich 37 Summary JavaScript is object based not object oriented a scripting language loosely typed JavaScript provides object types and permits a number of approaches for user created objects some are little more than associative arrays some demonstrate class-like behaviour with inheritance JavaScript prototypes lie at the heart of the language available to users JSON provides serialisation of JavaScript object properties required if data is to be transported slightly more advanced than name value pairs slightly lighter than XML but without readability and validation

JavaScript 4 © 2015the University of Greenwich 38 Any Questions?