Calling APIs from JavaScript
The browser can ask the server for data without reloading the page. You will call APIs with fetch and async/await, and load MVC partial views into a page.
Updated
Fetch and Async/Await
- Fetch (Apprentice): The browser's fetch function sends HTTP requests from JavaScript and returns a promise of the response. Chain .then to read the JSON, check response.ok before trusting it, and pass an options object to POST, PUT or DELETE.
- Async and Await (Journeyman): JavaScript has async and await too, working just like C#'s. An async function can await a promise, such as fetch's, and read like ordinary code, with try and catch for errors. Use it to load data into the page and send a form to an API.
MVC Partials with fetch
- MVC Partials with fetch: an overview (Journeyman): An MVC page can reload just one part of itself. JavaScript fetches the new part's HTML from an action that returns a partial view, and swaps it in. That's the MVC way to do what an API and JSON do for a JavaScript-built page.
- Using the fetch API (Journeyman): Catch the pager's clicks with one listener on the pager, cancel them with preventDefault, fetch the partial's HTML with fetch and response.text, and put it in the page with innerHTML. The links keep working when JavaScript doesn't run.
Exercise: Load a Partial View with fetch
- Exercise: Load a Partial View with fetch (Journeyman): Give BooksPlus a search that updates as you type. Move the results into a partial view, add an action that returns just that partial, and write the JavaScript that fetches it on every keystroke, while the plain search form keeps working.