Download presentation
Presentation is loading. Please wait.
Published byIvan Sanjaya Modified over 5 years ago
1
HTML5 AJAX & JSON APIs
2
Class Outline AJAX JSON JSONP What Is Ajax? Ajax: The Basics
Ajax the jQuery Way AJAX Exercises JSON What is JSON? JSON Array Object Example Much Unlike XML Because JSON Syntax JSON Objects & Arrays JSON HTTP Request Example JSON Exercises JSONP What is JSONP? How JSONP it works Cross-domain requests using a proxy server Security concerns 12/28/2018 Copyright © Carl M. Burnett
3
What is AJAX? AJAX = Asynchronous JavaScript and XML.
AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously. Exchanging small amounts of data with the server Updates parts of a web page, without reloading the whole page. Examples of applications using AJAX: Google Maps, Gmail, YouTube, and Facebook.
4
XMLHttpRequest Processes the returned data using JavaScript
An event happens: XMLHttpRequest Object Created HttpRequest Sent Web Server processes the HttpRequest Creates a response and sends data back to Client. Processes the returned data using JavaScript Updates page content 7/14/2013 Copyright © Carl M. Burnett
5
Ajax the jQuery Way Using the load() Method - Loads an HTML file into a specified element on the page. Traditional Example: Short list of news headlines. Page loads - Five most recent news stories appear. Add links to let visitors choose what news stories are displayed. Linking are displayed in separate web pages Force visitors to move onto another web page. (non-AJAX) AJAX Example: Load the selected news stories into the news headlines box on the page. Each visitor click - browser requests a new HTML file for the headline box from the server Places that HTML into the headlines box Never leaves current page.
6
The get() and post() Methods
QUERY STRING URL products.php?prodID=18&sessID=1234 name/value pairs GET Method: $.get('rateMovie.php','rating=5'); POST method: $.post('rateMovie.php','rating=5'); $.post('rateMovie.php','rating=5&user=Bob');
7
The get() and post() Methods
OBJECT LITERAL TO STORE DATA { name1: 'value1', name2: 'value2' } var data = { rating: 5 }; $.post('rankMovie.php', { rating: 5 });
8
The get() and post() Methods
JQUERY’S SERIALIZE() FUNCTION FOR FORM DATA var str = $("formData").serialize(); $.get('login.php',formData,loginResults);
9
The get() and post() Methods
Processing Data from the Server 1 $('#message a').click(function() { 2 var href=$(this).attr('href'); 3 var querystring=href.slice(href.indexOf('?')+1); 4 $.get('rate.php', querystring, processResponse); return false; // stop the link }); selects every link (<a> tag) inside of another tag with an ID of message extracts the href attribute of the link extracts just the part after the ? in the URL using the slice() method the Ajax request using the GET method - results goes to “Callback Function” stops the normal link behavior and prevents the web browser from unloading the current page
10
The get() and post() Methods
Callback Function 1 function processResponse(data) { 2 var newHTML; 3 newHTML = '<h2>Your vote is counted</h2>'; 4 newHTML += '<p>The average rating for this movie is '; 5 newHTML += data + '.</p>'; 6 $('#message').html(newHTML); 7 }
11
The get() and post() Methods
Handling Errors $.get('rate.php', querystring,processResponse).error(errorResponse); function errorResponse() { var errorMsg = "Your vote could not be processed right now. "; errorMsg += "Please try again later."; $('#message').html(errorMsg); }
12
jQuery AJAX Exercises Complete the following jQuery AJAX Exercises on W3Schools Website. jQuery AJAX Example jQuery load() Method jQuery $.get() Method jQuery $.post() Method
13
What is JSON? JSON stands for JavaScript Object Notation
JSON is a lightweight data-interchange format JSON is language independent * JSON is "self-describing" and easy to understand
14
JSON Array Object Example
{ "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] }
15
Much Unlike XML Because
JSON doesn't use end tag JSON is shorter JSON is quicker to read and write JSON can use arrays
16
JSON Syntax JSON syntax is derived from JavaScript object notation syntax: Data is in name/value pairs Data is separated by commas Curly braces hold objects Square brackets hold arrays
17
JSON Data - A Name and a Value
"firstName" : "John" JSON values can be: A number (integer or floating point) A string (in double quotes) A Boolean (true or false) An array (in square brackets) An object (in curly braces) null
18
JSON Objects JSON Arrays {"firstName":"John", "lastName":"Doe"} {
"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] }
19
JSON Uses JavaScript Syntax
{ "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] } // returns John Doe employees[0].firstName + " " + employees[0].lastName;
20
JSON HTTP Request Example
1: Create an array of objects. 2: Create a JavaScript function to display the array. 3: Create a text file 4: Read the text file with an XMLHttpRequest HTTP Request Example
21
What is JSONP? JSONP (which stands for JSON with padding)
Technique to overcome: cross-domain restrictions imposed by browsers. allows data to be retrieved from foreign systems.
22
How JSONP it works Function call - myResponseFunction()
It is the "P" of JSONP (the "padding" around the pure JSON, or according to some the "prefix". myResponseFunction({"Name": "Foo", "Id": 1234, "Rank": 7});
23
How JSONP it works Server response that includes the JSONP function.
JSONP does not work with JSON-formatted results. The JSONP function invocation gets sent back The payload that the function receives, must be agreed-upon by the client and server. The browser provides the name of the callback function Named query parameter value - typically name “jsonp” or “callback” <script type="application/javascript" src=" </script>
24
Cross-domain requests using a proxy server
Newer browsers support CORS relax this constraint Cooperating proxy server does not have such restrictions Relays a browser request to a server in a separate domain Stores the result. Returns the JSON payload when the browser makes a second request. The xd_arbiter.php used by Facebook's JS SDK is a popular example of this cooperating server technique.[6]
25
Security Concerns Untrusted third-party code
Callback name manipulation and Reflected File Download Cross-site request forgery – (Exclusive use of cookies for determining if a request is authorized) Rosetta Flash - Adobe Flash Player (Fixed 2014)
26
JSONP Exercise Adding a Flickr Feed to Your Site
27
Class Review AJAX JSON JSONP What Is Ajax? Ajax: The Basics
Ajax the jQuery Way AJAX Exercises JSON What is JSON? JSON Array Object Example Much Unlike XML Because JSON Syntax JSON Objects & Arrays JSON HTTP Request Example JSON Exercises JSONP What is JSONP? How JSONP it works Cross-domain requests using a proxy server Security concerns 12/28/2018 Copyright © Carl M. Burnett
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.