Week 9

Resources

Homework Review

This is the code we wrote together in class. Hopefully, it helps with doing your homework.


function displayMovie(movie) {
  // Get the list and append a new list item to it
  var list = document.querySelector("#movies");
  var item = document.createElement("li");
  list.appendChild(item);

  // Create the title element and append it to the list item
  var title = document.createElement("div");
  title.textContent = movie.title;
  item.appendChild(title)
}

XMLHttpRequest

XMLHttpRequest (or XHR) is another javascript object that a browser provides. It is used for retrieving data from a URL for use in your code.

The following function uses XMLHttpRequest to get data from a url and then passes the data to another function to handle on success:

function get(url, success) {
  var xhr = new XMLHttpRequest();

  xhr.addEventListener("readystatechange", function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      success(JSON.parse(xhr.response));
    }
  });

  xhr.open("GET", url);
  xhr.send();
}

The above code is handy for getting some data from a URL (for example, the Reddit JSON API) to do something with in your final project!

jQuery has a method just like this, which you can call like this: $.get(url, callback).