Вы находитесь на странице: 1из 30

Unit 7: Ajax, JSON and API Essentials

Introduction to Ajax
Ajax is the acronym for Asynchronous JavaScript and XML

All moderns browsers provide an XMLHttpRequest object that is used to send an Ajax request to the web server and to receive the returned data from the server Ajax lets you receive data from a web server without reloading the page partial page refresh

Normal HTTP Request


How a normal HTTP request is processed
HTTP Request

`
Web Browser

HTTP Response (new page)

Web Server

Application Server (Scripts)

Database Server

Server returns an entire page for a normal HTTP request so the page has to be loaded into the browser

Ajax XMLHttpRequest
How an Ajax XMLHttpRequest is processed
XMLHttpRequest

`
Web Browser (JavaScript)

Response (Data only)

Web Server

Application Server (Scripts)

Database Server

An Ajax request sends an XMLHttpRequest object to get data and the server returns only the data JavaScript is used to send the request, process the returned data and script the DOM with the new data

Application Programming Interfaces


Web sites like YouTube and Twitter provide Application Programming Interfaces (APIs) that show how to use Ajax to get data from their sites This means you can get data from these sites to enhance your web pages

Common Formats
Format HTML XML JSON Description Hypertext Markup Language eXtensible Markup Language JavaScript Object Notation File extension html xml json

XML is an open-standard, device-independent format that must be parsed by JavaScript or jQuery in the browser For the most part, JSON files are smaller and faster than XML

XML Data
<?xml version="1.0" encoding="utf-8"?> <management> <teammember> <name>Agnes</name> <title>Vice President of Accounting</title> <bio>With over 14 years of public accounting ... </bio> </teammember> <teammember> <name>Wilbur</name> <title>Founder and CEO</title> <bio>While Wilbur is the founder and CEO ... </bio> </teammember> </management>

JSON Data
{"teammembers":[ { "name":"Agnes", "title":"Vice President of Accounting", "bio":"With over 14 years of public accounting ..." }, { "name":"Wilbur", "title":"Founder and CEO", "bio":"While Wilbur is the founder and CEO ..." } ]}

XMLHttpRequest Object
Method abort() open(method,ur l[,async][,use r][,pass]) send([data]) Property readyState responseText Event onreadystate An event that occurs when the state of the request changes. A numeric value that indicates the state of the current request: 0 is UNSENT, 1 is OPENED, 2 is HEADERS_RECIEVED, 3 is LOADING and 4 is DONE The content thats returned from the server in plain text format. Description Cancels the current request. Opens a connection for the request. The parameters let you set the method to GET or POST, set the URL for the request, set asynchronous mode to true or false and supply a username and password if authentication is required. When asynchronous is used, the application continues while the request is being processed. Starts the request. This method can include data that gets sent with the request. This method must be called after a request connection has been opened.

A few more methods and properties in Figure 14-3 on pg. 441

jQuery Shorthand Methods for Ajax


Method
load(url[,data][,success]) $.get(url[,data][,success][,dataType]) $.post(url[,data][,success[,dataType]) $.getJSON(url[,data][,success])

Description Load HTML data. Load data with GET response. Load data with a POST request. Load JSON data with a GET request.

Parameter url data success dataType

Description The string for the URL to which the request is sent. A map or string that is sent to the server with the request, usually to filter the data that is returned. A function that is executed if the request is successful. A string that specifies the type of data (html, xml, json, script or text). The default is XML.

Examples of Ajax methods


A load method
$(#solution).load(solutions.html);

A $.get method
$ .get(getmanager.php, name=agnes, showManager);

A $.getJSON method
$.getJSON(team.json, function(data){ // the statements for the success function }

Load Method to Load HTML Data


The load function can only load content from files on the same server as the page making the call.

<p>Which Vecta corp. solution are you interested in learning about?</p> <a id=vprospect href=#>vProspect 2.0</a> | <a id =vconvert href=#>vConvert 2.0</a> | < a id=vretain href=#>vRetain 1.0</a><br> <div id=solution></div>

Load HTML Data (cont)


The start of the second div element in the solutions.html file
<div id="vconvert"> <p><strong>vConvert 2.0</strong></p> <p><img src="images/logo_vconvert.gif" width="63" height="36" > Create a highly user-friendly ... </p> <ul> <li>Build a visual and functional user ... </li> <li>Cause the desired emotional response ...</li> ... </ul> </div>

The jQuery that loads the data


$(document).ready(function() { $("#vprospect").click(function() { $("#solution").load("solutions.html #vprospect"); }); $("#vconvert").click(function() { $("#solution").load("solutions.html #vconvert"); }); $("#vretain").click(function() { $("#solution").load("solutions.html #vretain"); }); });

$.get and $.post Method to Load XML


To test these, the files must be on a web server

The HTML div element that receives the data


<div id=team></div>

Load XML (cont)


The XML file (team.xml)
<management> <teammember> <name>Agnes</name> <title>Vice President of Accounting</title> <bio>With over 14 years of public accounting ... </bio> </teammember> ... </management>

The jQuery
$(document).ready(function(){ $.get("team.xml", function(data){ $("#team").html(""); $(data).find("management").children().each(function() { var xmlDoc = $(this); $("#team").append("<h3>" + xmlDoc.find("name").text() + "</h3>" + xmlDoc.find("title").text() + "<br>" + xmlDoc.find("bio").text() + "<br>"); }); }); });

$.getJSON Method to Load JSON Data


The HTML div element that receives the data <div id=team></div>

Load JSON Data (cont)


The JSON file (team.json) {"teammembers":[ { "name":"Agnes", "title":"Vice President of Accounting", "bio":"With over 14 years of public accounting... }, { "name":"Damon", "title":"Director of Development", "bio":"Damon is the Director of Development ... " } ]} The jQuery $(document).ready(function(){ $.getJSON("team.json", function(data){ $.each(data, function() { $.each(this, function(key, value) { $("#team").append( "Name: " + value.name + "<br>" + "Title: " + value.title + "<br>" + "Bio: " + value.bio + "<br><br>" ); }); }); }); });

Send Data with an Ajax Request


When you send data with an Ajax request, the URL is for a server-side script such as a PHP file. Then, the script is responsible for returning the data in XML or JSON format.

Two Ways to Send Data with Ajax


A $.get method that uses a string for the data parameter $(document).ready(function() { $.get("getmanager.php", "name=wilbur", showManager); function showManager(data) { // process data } }); A $.get method that uses a map for the data parameter $(document).ready(function() { $.get("getmanager.php", {name:wilbur}, showManager); function showManager(data) { // process data } });

Helper Methods for Working with Ajax


Function serialize() serializeArray() Description Encode a set of form elements as a string that can be used for the data parameter of an Ajax request. Encode a set of form elements as an array of name/value pairs that can be used for the data parameter of an Ajax request.

The HTML for a form


<form id=contactForm> <!-- the controls for the form --> </form>

jQuery that uses the serialize method


$(document).ready(function() { var formData = $("#contactForm").serialize(); $.get("processcontact.php", formData, processReturnedData); function processReturnedData(data) { // the statements for the success function } });

How to use $.ajax method for Working with Ajax


The $.ajax method provides options that give you more control over the way the Ajax request works, such as providing a function for handling errors jqXHR object is jQuerys superset of the standard XMLHttpRequest object that provides the properties of that object JSONP or JSON with padding is a complement to JSON data that lets you request data from a server in a different domain

Options for the $.ajax Method


Options url beforeSend(jqXHR, settings) cache data complete(jqXHR, status) Descriptions The string for the URL to which the request is sent. A function that is executed before the request is sent. It can pass two parameters: the jqXHR object and a map of the settings for this object. A Boolean value that determines if the browser can cache the response. A map or string that is sent to the server with the request, usually to filter the data that is returned. A function that is executed when the request finishes. It can receive two parameters: the jqXHR object and a string that represents the status of the request.

More options in Figure 14-10 on pg. 425

$.ajax Method to Load Data


The HTML div element that receives the data <div id=team></div>

$.ajax Method (cont)


The XML file
<management> <teammember> <name>Agnes</name> <title>Vice President of Accounting</title> <bio>With over 14 years of public accounting ... </bio> </teammember> ... </management>

$.ajax Method (cont)


The jQuery for the $.ajax Method
$.ajax({ type: "get", url: "team.xml", beforeSend: function() { $("#team").html("Loading...");}, timeout: 10000, error: function(xhr, status, error) { alert("Error: " + xhr.status + " - " + error); dataType: "xml", success: function(data) { $("#team").html(""); $(data).find( "management").children().each(function() { var xmlDoc = $(this); $("#team").append("<h3>" + xmlDoc.find("name").text() + "</h3>" + xmlDoc.find("title").text() + "<br>" + xmlDoc.find("bio").text() + "<br>"); }); } });

Ajax with the API for Googles Blogger


Blogger is a free, Google application that lets you create your own blog All blogs are assigned a blog id that you must use along with your API key to get the JSON feed for your blog A blog consists of posts, comments, pages and users and the API documentation shows how to work with all of them

Online JSON Editor to Review Feed


When the documentation for an API is difficult to understand, you can often save time by reviewing the data in the JSON feed for an application. That way, you can tell exactly what data your application is going to get. www.jsoneditoronline.org

Procedure for Reviewing a Feed


1. Type or paste the URL for the feed into the address bar of your browser. Then, press the Enter key to see the contents of the JSON feed in your browser window. 2. Copy all of the JSON, go to the URL for the online JSON editor (above) and paste the JSON into the left pane of the editor. 3. Click the Format button at the top of the left pane to see the formatted JSON data. 4. Click the right arrow button between the panes to see a structured version of the data. Then, click on Expand All button at the top of the right pane to see all of the data in the feed.

Ajax and JSON To Display Blogger Posts

<div id=posts></div>

Blogger (cont)
jQuery for Using Blogger
var apikey = ""; // set this to your API key var html = ""; $.support.cors = true; $(document).ready(function() { $.ajax({ // the number in the url is the id for the blog url:"https://www.googleapis.com/blogger/v2/blogs/ 8698899267502010836/posts?key=" + apikey, dataType: "json", success: function(data) { $.each(data.items, function(index, value) { html += "<h3><a href='" + value.url + "'>" + value.title + "</a></h3>" + value.content + "<br>Posted by <a href='" + value.author.url + "'>" + value.author.displayName + "</a>"; }); // end each method $("#posts").html(html); } // end ajax options }); }); // end ajax and ready methods

Вам также может понравиться