All of the pages that we've made up until now have content, style, and behavior.
Web applications are webpages that pull in additional data and information as the user progresses through them, making it feel similar to a desktop application.
Some motivations for making web pages into web applications:
Using javascript to pull in more content from the server without navigating the page to a new url
fetch('hidden/data.txt').
then(function(response){
response.text().then(function(text){
alert(text);
});
});
Your code waits for the request to completely finish before proceeding. Might be easier for you to program, but the user's entire browser LOCKS UP until the download is completed, which is a terrible user experience (especially if the page is very large or slow to transfer)
What is XML
? An older data format that we wont use in this class.
Why is XML
part of the acronym then? Because it's too late to change the acronym.
the fetch
function can be used to fetch anything that you can fetch with your browser.
This includes HTML, plain text, media files and, as we will soon learn, JSON.
Use the inspector, watch the network tab to see the requests that go out.
Generally speaking, you can only send Ajax requests to the server that your page came from.
This is to prevent rogue javascript from being able to call out to any server and pull in whatever content it wants to.
This is a little bit of a concern for us, because we want you guys to call out to the webster
server to get new information, so we have to write special rules on webster
to allow your
programs to do what's called "Cross-Origin Request Sharing" or CORS
Promises have three states:
Example: “I promise to post homework 4”
Pending: Not yet posted
Fulfilled: Homework 4 posted
Rejected: Wrong homework posted, or not posted in time
let promise = // some Promise....;
promise.
then( function( params... ) {
// Promise resolved -- handle success
} );
catch( function( params... ) {
// Promise rejected -- handle failure
} );
The help deal with uncertainty in your code. You never know exactly what will happen or when it will happen when you make an Ajax call, so wrapping the call in a Promise is a nice way to deal with the uncertainty.
You also define what happens after the Promise fulfills with the then
function, and what happens
when it rejects in the catch
function.
//include this code, based on: https://developers.google.com/web/updates/2015/03/introduction-to-fetch
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response.text();
} else {
return Promise.reject(new Error(response.status+": "+response.statusText));
}
}
function callAjax(){
let url = ..... // put url string here
fetch(url, {credentials: 'include'}) // include credentials for cloud9
.then(checkStatus)
.then(function(responseText) {
//success: do something with the responseText
})
.catch(function(error) {
//error: do something with error
});
}