Introducing 

Prezi AI.

Your new presentation assistant.

Refine, enhance, and tailor your content, source relevant images, and edit visuals quicker than ever before.

Loading…
Transcript

http request

  • URL: host, path, credentials
  • parameters: names and values, usually combined with URL
  • headers: names and values, sent separately
  • content/payload: one “blob” of data

protocol

path

http://headmaster.cs.lmu.edu/headmaster/students?q=smith&class=sophomore

parameters

host

  • Note how some URL characters are necessarily “special:” : / ? &
  • Headers are part of the request but not typically user-visible
  • Ditto for the body/content/payload

data data data

web application servers

Sometimes, the representation (model) of a database does not directly match the constructs of the language in which a web service is written—this is when some type of mapping is necessary, the more automated the better

For example, when an object-oriented language like Java interacts with a relational database like PostgreSQL, it is convenient to have object-relational mapping (ORM): automated or semi-automated conversion between objects and relational constructs (rows, columns, etc.)

Modern database implementations vary widely, ranging from traditional relational database management systems to more recently-developed “big data” or “NoSQL” systems that use alternative and sometimes simpler data models

At this level, the concern is solely the proper management and efficient retrieval of information—major concepts include:

  • Domain objects—What are the “nouns” in an application, what properties or attributes do they have, and how are they related to each other?

  • CRUD—The standard data manipulation operations: create, retrieve, update, and delete

  • ACID—The standard database implementation requirements: atomicity, consistency, isolation, durability

web browsers

Web application servers, as the direct “feeders” of HTML, CSS, JavaScript, and other data to web browsers, typically have the following functionality:

  • Templating—Maintains consistent layouts and shared components for web pages

  • Server-side dynamic content—Injects data or customization into a web page before it is sent to the web browser (a.k.a. “the old way”—but still useful in certain cases)

  • Session management—Maintains individual application “instances” and state, per user

  • Login/logout—Tracks whether a user is logged in, along with relevant data for that user; redirects to login page when necessary; times users out

  • Web page authorization—In association with login/logout, tracks which pages may be seen by which user

  • Service relay—Due to the same-origin policy, web pages might access web services through the web application server, which acts as a relay for requests and responses

http response

  • headers: names and values, sent separately
  • Status—How’d it go?
  • Content-Type—What are you getting back?
  • Many, many more

  • content/payload: most of the time, viewed as the “actual” response (what Content-Type refers to)

media

(image, audio, video, plug-in, etc.)

CSS

(cascading style sheets)

HTML

(hypertext markup language)

An HTML document is a tree of elements, which are defined using tags or markup

This element tells the browser that the page is in HTML5

CSS consists of rules in curly-brace delimited blocks

The link element associates an HTML page with a CSS file—there may be more than one link element, and they should all be in the head

Some elements stand alone—they have a single tag and typically have a slash as the last character

Proficiency in CSS can be broken down into two areas:

  • Knowing the full power and range of selectors
  • Knowing the properties that are available to use

<!doctype html>

<html>

<head>

<meta charset="UTF-8"/>

<title>Hello</title>

<link rel="stylesheet" href="http://bootstrapcdn.com/bootstrap.css"/>

</head>

<body>

<p>HTML!</p>

<script src="http://code.jquery.com/jquery.min.js"></script>

<script src="http://bootstrapcdn.com/bootstrap.js"></script>

</body>

</html>

<!doctype html>

<html>

<head>

<meta charset="UTF-8"/>

<title>Hello</title>

</head>

<body>

<p>HTML!</p>

</body>

</html>

Keep your markup readable by indenting one level for child elements

Each block begins with a selector—this identifies the elements for which the properties within should apply

Some elements have one or more attributes, expressed as a name followed by an equals sign and a value in double-quotes

The script element associates an HTML page with JavaScript code—there may also be more than one script element in the page

The properties are name-value pairs separated by colons; the properties themselves are separated by semicolons

Although script elements may go anywhere, their preferred location is the end of the body—this allows the web browser to display the page before it interprets and executes the JavaScript code

(Note that file references are given in the href attribute for link but in the src attribute for script)

body {

background-color: whitesmoke;

margin-left: 4em;

}

.fineprint {

color: gray;

font-size: 8px;

}

#main-headline {

text-shadow: 0 4px 8px #aaa;

}

.code > p:first-child {

border-bottom: 1px solid black;

}

Some elements contain children or text content—they have start and end tags, where the end tag begins with a slash

The top-level element is html, which in turn contains a head and a body—the head then must have at least a meta charset and a title, while the body can have pretty much anything

<body>

.

.

.

<div class="fineprint">

.

.

</div>

.

.

<span id="main-headline">...</span>

.

<div class="code">

<p>Example</p>

.

.

</div>

.

.

.

</body>

Many web page development libraries come with CSS—they’ve taken the trouble of defining a visual system for you, so you don’t have to start from scratch

More notes on the sequential execution of script elements

JavaScript code is read and executed in the order that script elements appear

Many scripts require that an entire page be loaded before they can do their job

As much as possible, “wrap” distinct execution units in functions in order to encapsulate variables—remember to call them right away

Many JavaScript libraries (like jQuery) execute code that defines top-level objects which your code can then use (jQuery defines $):

Things to do with JavaScript

But because script elements can appear anywhere, and they are executed as the browser comes across them, it is nice to have a guaranteed mechanism that runs code only when the browser has finished processing a web page

This might be stating the obvious, but what the hey:

  • JavaScript code allows a web page to be truly “dynamic” (the latest CSS version provides some, but not in a truly general way)

  • This dynamic behavior is typically triggered by events, which result from either user actions or concurrent activity, such as the passage of time or network connections

  • In response to such events, JavaScript code changes the content of the web page (the DOM) “in situ”—ergo, “dynamic” web pages

var SuperLib = (function () {

.

.

.

return {

twice: function (f, parameter) {

return f(f(parameter));

},

.

.

.

};

})();

jQuery provides a variant for this technique by sending a function into yet another function—the global jQuery object (which has the convenient alias $):

$(function () {

.

.

.

}); // Note how we don’t call the function here.

(function () {

// Variables have function scope (so far).

var i, max, dateElement;

// You get some familiar constructs...

for (i = 0, max = 5; i < max; i += 1) {

.

.

.

}

// ...and access to the entire web page that invoked this code.

dateElement = document.getElementById("date");

dateElement.innerHTML = document.lastModified;

dateElement.style.color = "pink";

// Many developers prefer helper libraries like jQuery over the

// native API for manipulating a web page, known as the DOM

// (Document Object Model).

$("#date")

.text(document.lastModified)

.css({ color: "pink" });

})();

The cycle of displaying a web page, waiting for events to happen, then responding to events in a way that modifies or updates that web page, is a paradigm known as event-driven programming—and the major roles in this cycle consist of the model, the view, and the controller (MVC)…which you have actually already seen…

Two footnotes on this:

  • Putting scripts at the end of the body obviates the need for this, if you can guarantee that they will end up there
  • You don’t need jQuery to have this “on load” guarantee—but jQuery’s way is a convenient, compact way for doing this

Because JavaScript code is read in the order that script elements appear on the web page, references to JavaScript libraries are made before references to code that depends on these libraries (including other libraries)

anything else

(documents, code, plain text, tarballs, etc.)

JavaScript

(not an acronym)

How does jQuery Ajax thee—let us count the ways

Instead of multiple parameters, ajax takes a single object whose properties play the role of “arguments” to this function

jQuery provides more than one function for making Ajax connections, varying mainly in terms flexibility and simplicity

In addition to getJSON, jQuery provides get (which can handle non-JSON responses) and post (for sending representations to the web service)

These functions are all “shorthand” for the mother of all Ajax functions, simply known as, well, ajax

At a minimum, getJSON is given the URL to GET, then the function to call upon receiving the response

Because we just came from talking about JSON, let’s start with one of the simpler jQuery Ajax functions: getJSON

getJSON can also be given query parameters—if you have these, supply them as the second argument, between the URL and the success callback

The function to call upon success is known as a callback—this is why the first “A” in Ajax stood for “asynchronous”

$.ajax({

type: "PUT",

url: "http://us.battle.net/api/d3/profile/" + playerName,

data: JSON.stringify(updatedProfile),

contentType: "application/json",

success: function () {

$("#success-alert").fadeIn();

},

error: function () {

$("#error-alert").fadeIn();

}

});

This is only a small subset of the full range of settings you can specify for your Ajax call—check the jQuery API documentation to see all of them

Get used to callbacks—they’re everywhere in modern JavaScript

These functions can take certain parameters also—repeat after me: “check the API documentation”

Most of the time, you only care about the first argument to the callback: the data that was returned by the web service

(the meaning of the other two arguments can be found in the jQuery API documentation, though you might be able to guess them based on their names)

// We assume that at this point, the code is handling an

// event or otherwise responding to some page activity.

$.getJSON(

"http://us.battle.net/api/d3/profile/" + playerName,

function (data, textStatus, jqXHR) {

var i, max;

// jQuery transparently converts the JSON representation

// into its equivalent object.

//

// Assume that the object has a battleTag property which

// is a basic string.

$("#battle-tag-container").text(data.battleTag);

// Assume also that data has an array called heroes.

for (i = 0, max = data.heroes.length; i < max; i += 1) {

displayHero(data.heroes[i]);

}

}

);

As an exercise, try implementing getJSON, get, and post in terms of ajax (they’re called “shorthand” for a reason)

Make sure that you are comfortable with JavaScript’s scoping rules so that you know what your callbacks can or cannot see

http request

query on the collection resource

Multiple strategies have been developed regarding how web service URLs should be formed (the service’s “API,” as they say)

http://headmaster.cs.lmu.edu/headmaster/students?q=smith&class=sophomore

The current best practice is an approach known as REST, short for Representational State Transfer

web service root

collection resource

http://headmaster.cs.lmu.edu/headmaster/events/07281969

The primary rules of REST are:

  • Every URL represents a resource (or vice versa—every resource has a URL)

  • Some resources are collections of further resources, and are indicated with a URL that sounds plural

  • Such collections may be queried, or individual members may be accessed directly through unique, stable URLs

  • Not surprisingly, “leaf” resources also have a unique, stable URL (sometimes within their designated collection)

  • Resource access and manipulation always use the same URL, but with varying methods: GET, POST, PUT, DELETE, etc.

“leaf” resource

Every URL request pertains to the state of that resource at that moment and at that moment only, with the content of the request or response typically transferring a representation of the state of that resource at that time (which is why REST is called REST)

http response

Just as RESTful requests follow certain rules or conventions, RESTful responses do the same:

  • The response to a successful GET request has a response Status header of OK (200) with a representation of the state of the requested resource at that moment in the response payload

  • Unsuccessful GETs (and other request methods) are communicated through the Status header of the response

  • POSTs add a new resource (whose representation is in the request payload) to a collection—on success, two headers are involved: Status of Created (201), and Location, holding the URL of the newly-added resource

  • PUTs either modify an existing resource or add a new resource, pending the validity of the URL that is being PUT for such a resource—successful modifications return simply a Status of No Content (204) while successful additions return a Status of Created (201): no need for a Location because the successful PUT already went to that URL

Typical errors include:

  • 400 Bad Request—something was wrong with the request, like a bad or missing parameter

  • 403 Forbidden—many service APIs require authentication and authorization, or else they respond with this

  • 404 Not Found—the URL in the request maps to a non-existent resource

  • 500 Internal Server Error—something went wrong “behind” the web service: in other words, “It’s not you, it’s me”

JSON, short for JavaScript Object Notation, is a hugely popular (and very convenient) representation scheme for web service resources—it is none other than a JavaScript literal for objects or arrays:

Coming full circle: we talked about web services because connections to them constitute one of the major activities of JavaScript in a web page

This network activity has a name—Ajax

Square brackets delimit arrays, holding comma-separated lists of typically, but not necessarily, the same type of object or value

Ajax used to be an acronym, but now it is simply the name for what happens when JavaScript code in a web page connects to a web service to acquire or modify information

Like the DOM, there is a “browser-native” way to do Ajax—this would be the XMLHttpRequest object

[

{

"name": "Yharr",

"id": 1,

"level": 60,

"hardcore": false,

"gender": 0,

"lastUpdated": 1341343147,

"dead": false

},

{

"name": "Worm",

"id": 2,

"level": 19,

"hardcore": true,

"gender": 0,

"lastUpdated": 1339289897,

"dead": false

},

{

"name": "Korale",

"id": 3,

"level": 18,

"hardcore": false,

"gender": 0,

"lastUpdated": 1344055324,

"dead": false

}

]

Unfortunately, doing it this way can be awkward and generate a lot of repeated code

Curly braces delimit objects, which are comma-separated lists of name-and-value pairs—in JSON, names are enclosed in quotes and colons separate names from values

  • The name-in-quotes requirement is one difference between JSON and JavaScript object literals

  • One nice side effects of delimited names: they facilitate names with certain non-alphanumeric characters, like text-color (don’t go crazy on them though—this is not Mount Everest)

Fortunately, jQuery provides a much cleaner approach to Ajax…and so we go back to JavaScript on the client side (the web browser)

(If you really must know, Ajax used to stand for “Asynchronous JavaScript and XML,” XML being an resource state representation scheme that predates the rise of JSON…you can see now why it’s better to drop the acronym, because “AJAJ” just doesn’t quite have the same ring to it)

The rest of the specifics for what goes into a particular web service’s JSON representations are pretty much up to the web service—thus, that service’s providers must provide good documentation if they expect others to use their API

data

(JSON, etc.)

anything else

(documents, media, plain text, tarballs, etc.)

web services

desktop & mobile

applications

http request

Web services, which handle resource information only, typically provide the following (but also via HTTP request/response):

  • Authentication and authorization—If needed, requests must present credentials to avail of a web service

  • Parsing and serialization—Web service code typically manipulates data in some language-specific manner (e.g., Java objects), so these need to be parsed from a request as they come in, or serialized into the response as they go out

  • URL-to-code mapping—In general, a URL must find its way to code that processes that URL; thus, it is convenient to have an easy mechanism for declaring which URLs go to which code/methods/functions

  • Database access—Many resource types are ultimately stored in a database of some sort, and web services function as gateways into that database: clients do not interact with the database directly

http response

Learn more about creating dynamic, engaging presentations with Prezi