Professional Documents
Culture Documents
// creating an array to contain the HTML strings // Creates an empty array to contain the HTML strings // Creates an empty array to contain the HTML strings
let wordList = [] let wordList = []; let wordList = [];
// looping through the response and maxxing out at 10 // Loops through the response and caps off at 10 // Loops through the response and caps off at 10
for(let i = 0; i < Math.min(res.length, 10); i++){ for(let i = 0; i < Math.min(res.length, 10); i++){ for(let i = 0; i < Math.min(res.length, 10); i++){
// creating a list of words // creating a list of words // creating a list of words
wordList.push(`<li>${res[i].word}</li>`) wordList.push(`<li>${res[i].word}</li>`); wordList.push(`<li>${res[i].word}</li>`);
} } }
// joins the array of HTML strings into one string // Joins the array of HTML strings into one string // Joins the array of HTML strings into one string
wordList = wordList.join("") wordList = wordList.join(""); wordList = wordList.join("");
// manipulates responseField to render the modified // Manipulates responseField to render the modified // Manipulates responseField to render the modified
response response response
responseField.innerHTML = `<p>You might be interested responseField.innerHTML = `<p>You might be interested responseField.innerHTML = `<p>You might be interested
in:</p><ol>${wordList}</ol>` in:</p><ol>${wordList}</ol>`; in:</p><ol>${wordList}</ol>`;
return return return
} } }
// Renders response before it is modified // Renders response before it is modified // Renders response before it is modified
const renderRawResponse = (res) => { const renderRawResponse = (res) => { const renderRawResponse = (res) => {
// taking the first 10 words from res // Takes the first 10 words from res // Takes the first 10 words from res
let trimmedResponse = res.slice(0, 10) let trimmedResponse = res.slice(0, 10); let trimmedResponse = res.slice(0, 10);
//manipulates responseField to render the unformatted // Manipulates responseField to render the unformatted // Manipulates responseField to render the unformatted
response response response
responseField.innerHTML = responseField.innerHTML = responseField.innerHTML =
`<text>${JSON.stringify(trimmedResponse)}</text>` `<text>${JSON.stringify(trimmedResponse)}</text>`; `<text>${JSON.stringify(trimmedResponse)}</text>`;
} } }
// Renders the JSON that was returned when the Promise // Renders the JSON that was returned when the Promise from // Renders the JSON that was returned when the Promise
from fetch resolves. fetch resolves. from fetch resolves.
const renderJsonResponse = (res) => { const renderJsonResponse = (res) => { const renderJsonResponse = (res) => {
// creating an empty object to store the JSON in key-value // Creates an empty object to store the JSON in key-value // Creates an empty object to store the JSON in key-value
pairs pairs pairs
let rawJson = {} let rawJson = {}; let rawJson = {};
for(let key in response){ for(let key in res){ for(let key in response){
rawJson[key] = response[key] rawJson[key] = res[key]; rawJson[key] = response[key];
} } }
// converting JSON into a string and adding line breaks to // Converts JSON into a string and adding line breaks to make // Converts JSON into a string and adding line breaks to
make it easier to read it easier to read make it easier to read
rawJson = JSON.stringify(rawJson).replace(/,/g, ", \n") rawJson = JSON.stringify(rawJson).replace(/,/g, ", \n"); rawJson = JSON.stringify(rawJson).replace(/,/g, ", \n");
// manipulates responseField to show the returned JSON. // Manipulates responseField to show the returned JSON. // Manipulates responseField to show the returned
responseField.innerHTML = `<pre>${rawJson}</pre>` responseField.innerHTML = `<pre>${rawJson}</pre>`; JSON.
} } responseField.innerHTML = `<pre>${rawJson}</pre>`;
}
// AJAX function
const getSuggestions = () => {
const wordQuery = inputField.value;
const topicQuery = topicField.value;
const endpoint =
`${url}${queryParams}${wordQuery}${additionalParams}${topicQuery}`;
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
renderResponse(xhr.response);
}
}
xhr.open('GET', endpoint);
xhr.send();
}
submit.addEventListener('click', displaySuggestions);
// Formats response to look presentable on webpage
const renderResponse = (res) => {
// handles if res is falsey
if(!res){
console.log(res.status)
}
// in case res comes back as a blank array
if(!res.length){
responseField.innerHTML = "<p>Try again!</p><p>There were no
suggestions found!</p>"
return
}
// Renders the JSON that was returned when the Promise from fetch
resolves.
const renderJsonResponse = (res) => {
// creating an empty object to store the JSON in key-value pairs
let rawJson = {}
for(let key in response){
rawJson[key] = response[key]
}
// converting JSON into a string and adding line breaks to make it
easier to read
rawJson = JSON.stringify(rawJson).replace(/,/g, ", \n")
// manipulates responseField to show the returned JSON.
responseField.innerHTML = `<pre>${rawJson}</pre>`
}
// AJAX function
const getSuggestions = () => {
const wordQuery = inputField.value;
const endPoint = dataMuseUrl + queryParams +
wordQuery;
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
renderWordResponse(xhr.response);
}
};
xhr.open('GET', endPoint);
xhr.send();
}
submit.addEventListener('click', displaySuggestions);
// element selector
const shortenButton =
document.querySelector('#shorten');
// AJAX functions
const shortenUrl = () => {
const urlToShorten = inputField.value;
const data = JSON.stringify({destination:
urlToShorten});
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
renderByteResponse(xhr.response);
}
};
xhr.open('POST', rebrandlyUrl);
xhr.setRequestHeader('Content-type',
'application/json');
xhr.setRequestHeader('apikey', apiKey);
xhr.send(data);
}
responseField.removeChild(responseField.firstChild);
};
shortenUrl();
};
shortenButton.addEventListener('click',
displayShortUrl);
// wordSmith helperFunctions are on lines 4 - 50
// byteSize helperFunctions are on lines 52 - 76
responseField.innerHTML = `${structuredRes}`;
}
}
JavaScript é a linguagem da web por causa de seus recursos assíncronos. AJAX, que significa JavaScript
assíncrono e XML, é um conjunto de ferramentas que são usadas juntas para aproveitar os recursos assíncronos do
JavaScript.
Existem muitos métodos de solicitação HTTP, dois dos quais são GET e POST.
Solicitações GET solicitam apenas informações de outras fontes.
Os métodos POST podem introduzir novas informações para outras fontes, além de solicitá-las.
Pedidos GET podem ser escritos usando um objeto XMLHttpRequest e JavaScript baunilha.
Solicitações POST também podem ser escritas usando um objeto XMLHttpRequest e JavaScript baunilha.
Escrever solicitações GET e POST com objetos XHR e baunilha JavaScript requer a construção do objeto XHR
usando new, definindo responseType, criando uma função que manipulará o objeto de resposta e abrindo e
enviando a solicitação.
Para adicionar uma string de consulta a um endpoint de URL, você pode usar ?e incluir um parâmetro.
Para fornecer parâmetros adicionais, use &e inclua um par de valores-chave, associado por =.
Determinar como escrever corretamente as solicitações e como implementá-las corretamente requer ler
atentamente a documentação da API com a qual você está trabalhando.
1. As solicitações GET e POST podem ser criadas de várias formas.
2. Use AJAX para solicitar dados de forma assíncrona de APIs. fetch()e async/ awaitsão novas
funcionalidades desenvolvidas em ES6 (promessas) e ES8 respectivamente.
3. Promessas são um novo tipo de objeto JavaScript que representa dados que serão retornados de
uma solicitação.
4. fetch()é uma API da web que pode ser usada para criar solicitações. fetch()irá retornar
promessas.
5. Podemos encadear .then()métodos para lidar com promessas retornadas por fetch().
6. O .json()método converte uma promessa retornada em um objeto JSON.
7. async é uma palavra-chave usada para criar funções que retornarão promessas.
8. await é uma palavra-chave que é usada para dizer a um programa para continuar se movendo
pela fila de mensagens enquanto uma promessa é resolvida.
9. awaitsó pode ser usado dentro de funções declaradas com async.