10. Event Loop and Asynchronous Behavior
Activity 10.01: Movie Browser Using XHR and Callbacks
Solution:
- In the
script.ts
file, locate thesearch
function and verify that it takes a single string parameter and that its body is empty. - Construct a new
XMLHttpRequest
object:const xhr = new XMLHttpRequest();
- Construct a new string for the search result URL using the
getSearchUrl
method:const url = getSearchUrl(value);
- Call the
open
andsend
methods of thexhr
object:xhr.open('GET', url); xhr.send();
- Add an event handler for the
xhr
object'sonload
event. Take the response and parse it as a JSON object. Store the result in a variable of theSearchResultApi
interface. This data will have the results of our search in aresults
field. If we get no results, this means that our search failed:xhr.onload = function() { ...