Chapter 20. XHR: loading data
This chapter covers
- Loading data with the XMLHttpRequest object
- Calling functions once the data loads
- Updating views with loaded data
- JavaScript Object Notation (JSON)
- Converting JSON text into JavaScript objects
A calendar or movies database or adventure game can use a lot of data. A news site may have up-to-the-minute updates with breaking news and sports scores. It’s not always desirable to load all of the data at once or for a visitor to have to keep refreshing a web page to get the latest information. It would be great if a page could access just the pieces of new data it needs to stay fresh, even after it has loaded. Stock prices, tweets, comments, scores, and, yes, the current health of zombies can all be updated independently without a full page reload.
This chapter shows you how to reach out across the internet and grab data for your apps while they’re running. In particular, you load exercise data as you switch between users in the fitness app, and you load location data, tomb by tomb, as players solve the riddles of The Crypt.
You and your team have been building a fitness app that lets users track their exercise (see chapters 14 to 16). The app can convert JavaScript data into user models, use a choice of views to display user info on the console, and accept user input at the console prompt. The tasks you were given for the project are these:
1. Retrieve user data as a string.