1 of 9

AJAX + Web Services

CS 330: Intro to programming with JavaScript

1

2 of 9

Outline

  1. Template Literals
  2. Intro to Ajax + Fetch

2

3 of 9

1. Review: Template Literals

  • Template literals are strings that allow you to embedded expressions
  • They’re convenient for generating larger chunks of HTML from lists of objects
  • Uses the “backtick character”

3

4 of 9

let name = 'Walter';

console.log( ` Some string.

Can be multiple lines.

Can have expressions ${2 + 2}� ${name} ` );

4

5 of 9

1. Review: Template Literals

  • Example 1: Simple
  • Example 2: With a For / Of Loop

5

6 of 9

2. Intro to AJAX

AJAX

  • AJAX: Stands for Asynchronous JavaScript and XML
  • Enables JavaScript to make server requests and (optionally) update the current screen
  • Not easy to tell that information is even being transmitted to/from a server
  • Came on the scene ~2004 (made popular w/Google Mail and Google Maps)

Now Ajax (lowercase) as a generic term for any client-side process which fetches data from a server and updates the DOM dynamically without a full-page refresh.

6

7 of 9

2. Intro to Fetch

JavaScript’s Fetch API

  • The Fetch API is a newer instantiation of asynchronous server-client web communication
  • Provides an interface for fetching resources (including across the network). The new API provides a more powerful and flexible feature set (improving upon AJAX)

7

8 of 9

Fetch Example

const url = 'https://www.apitutor.org/youtube/simple/?q=skateboarding+dog+&type=video';

fetch(url)� .then((response) => {// takes a response stream and reads it to completionreturn response.json();}).then((myJson) => {// once entire data stream has been retrieved, you can execute� // code that makes use of the data� console.log(myJson);});

8

9 of 9

9