chore(i18n,curriculum): processed translations (#43008)

This commit is contained in:
camperbot
2021-07-26 03:17:00 +09:00
committed by GitHub
parent 20c458bfe7
commit f02de3c64c
87 changed files with 858 additions and 850 deletions

View File

@ -1,6 +1,6 @@
---
id: 587d7fae367417b2b2512be4
title: Access the JSON Data from an API
title: Acessar os dados de JSON de uma API
challengeType: 6
forumTopicId: 301499
dashedName: access-the-json-data-from-an-api
@ -8,37 +8,37 @@ dashedName: access-the-json-data-from-an-api
# --description--
In the previous challenge, you saw how to get JSON data from the freeCodeCamp Cat Photo API.
No desafio anterior, você viu como obter dados de JSON da API de fotos de gatos do freeCodeCamp.
Now you'll take a closer look at the returned data to better understand the JSON format. Recall some notation in JavaScript:
Agora, dê uma olhada nos dados retornados para entender melhor o formato JSON. Vamos relembrar um pouco da notação do JavaScript:
<blockquote>[ ] -> Square brackets represent an array<br>{ } -> Curly brackets represent an object<br>" " -> Double quotes represent a string. They are also used for key names in JSON</blockquote>
<blockquote>[ ] -> colchetes representam um array<br>{ } -> chaves representam um objeto<br>" " -> aspas duplas representam uma string. Elas também são usadas para nomes de chaves em JSON</blockquote>
Understanding the structure of the data that an API returns is important because it influences how you retrieve the values you need.
Entender a estrutura dos dados que uma API retorna é importante, pois influencia a forma como você obtém os valores de que necessita.
On the right, click the `Get Message` button to load the freeCodeCamp Cat Photo API JSON into the HTML.
À direita, clique no botão `Get Message` para carregar o JSON da API de fotos de gatos do freeCodeCamp no HTML.
The first and last character you see in the JSON data are square brackets `[ ]`. This means that the returned data is an array. The second character in the JSON data is a curly `{` bracket, which starts an object. Looking closely, you can see that there are three separate objects. The JSON data is an array of three objects, where each object contains information about a cat photo.
O primeiro e o último caracteres que você verá nos dados do JSON serão colchetes `[ ]`. Isso significa que os dados retornados são um array. O segundo caractere nos dados do JSON é uma abertura de chave `{`, que marca o início de um objeto. Se olhar mais atentamente, você verá que há três objetos separados. Os dados do JSON são um array de três objetos, onde cada objeto contém informações sobre uma foto de gato.
You learned earlier that objects contain "key-value pairs" that are separated by commas. In the Cat Photo example, the first object has `"id":0` where `id` is a key and `0` is its corresponding value. Similarly, there are keys for `imageLink`, `altText`, and `codeNames`. Each cat photo object has these same keys, but with different values.
Você aprendeu anteriormente que objetos contêm "pares de chave-valor" separados por vírgulas. No exemplo de fotos de gatos, o primeiro objeto tem o `"id":0`, onde `id` é uma chave e `0` é o seu valor correspondente. Do mesmo modo, há chaves para `imageLink`, `altText` e `codeNames`. Cada objeto de foto de gato tem as mesmas chaves, mas com valores diferentes.
Another interesting "key-value pair" in the first object is `"codeNames":["Juggernaut","Mrs. Wallace","ButterCup"]`. Here `codeNames` is the key and its value is an array of three strings. It's possible to have arrays of objects as well as a key with an array as a value.
Outro "par chave-valor" interessante no primeiro objeto é `"codeNames":["Juggernaut","Mrs. Wallace","ButterCup"]`. Aqui, `codeNames` é a chave e seu valor é um array com três strings. É possível ter arrays de objetos, além de uma chave com um array como valor.
Remember how to access data in arrays and objects. Arrays use bracket notation to access a specific index of an item. Objects use either bracket or dot notation to access the value of a given property. Here's an example that prints the `altText` property of the first cat photo - note that the parsed JSON data in the editor is saved in a variable called `json`:
Lembre-se de como acessar dados em array e em objetos. Arrays usam a notação de colchetes para acessar um índice específico de um item. Objetos usam os colchetes ou a notação de ponto para acessar o valor de determinada propriedade. Aqui vemos um exemplo que imprime a propriedade `altText` da primeira foto de gatos - observe que os dados do JSON representados no editor são salvos em uma variável chamada `json`:
```js
console.log(json[0].altText);
```
The console would display the string `A white cat wearing a green helmet shaped melon on its head.`.
O console exibirá a string `A white cat wearing a green helmet shaped melon on its head.`.
# --instructions--
For the cat with the `id` of 2, print to the console the second value in the `codeNames` array. You should use bracket and dot notation on the object (which is saved in the variable `json`) to access the value.
Para o gato com o `id` de 2, imprima no console o segundo valor do array `codeNames`. Você deve usar notação de colchetes e de ponto no objeto (que é salvo na variável `json`) para acessar o valor.
# --hints--
Your code should use bracket and dot notation to access the proper code name, and print `Loki` to the console.
Seu código deve usar notação de colchetes e de ponto para acessar o nome do código apropriado e imprimir `Loki` no console.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7fad367417b2b2512be2
title: Change Text with click Events
title: Alterar texto com eventos de clique
challengeType: 6
forumTopicId: 301500
dashedName: change-text-with-click-events
@ -8,11 +8,11 @@ dashedName: change-text-with-click-events
# --description--
When the click event happens, you can use JavaScript to update an HTML element.
Quando ocorre o evento de clique, você pode usar o JavaScript para atualizar um elemento HTML.
For example, when a user clicks the `Get Message` button, it changes the text of the element with the class `message` to say `Here is the message`.
Por exemplo, quando um usuário clica no botão `Get Message`, ele muda o texto do elemento com a classe `message` para que passe a dizer `Here is the message`.
This works by adding the following code within the click event:
Isso ocorre quando adicionamos o seguinte código ao evento de clique:
```js
document.getElementsByClassName('message')[0].textContent="Here is the message";
@ -20,11 +20,11 @@ document.getElementsByClassName('message')[0].textContent="Here is the message";
# --instructions--
Add code inside the `onclick` event handler to change the text inside the `message` element to say `Here is the message`.
Adicione código ao manipulador de evento `onclick` para alterar o texto dentro do elemento `message` de modo que ele diga `Here is the message`.
# --hints--
Your code should use the `document.getElementsByClassName` method to select the element with class `message` and set its `textContent` to the given string.
O código deve usar o método `document.getElementsByClassName` para selecionar o elemento com ac classe `message` e definir o `textContent` como a string mencionada.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7fae367417b2b2512be5
title: Convert JSON Data to HTML
title: Converter dados do JSON para HTML
challengeType: 6
forumTopicId: 16807
dashedName: convert-json-data-to-html
@ -8,15 +8,15 @@ dashedName: convert-json-data-to-html
# --description--
Now that you're getting data from a JSON API, you can display it in the HTML.
Agora que você está recebendo dados de uma API de JSON, você pode exibir os dados no HTML.
You can use a `forEach` method to loop through the data since the cat photo objects are held in an array. As you get to each item, you can modify the HTML elements.
Você pode usar um método `forEach` para percorrer os dados, já que os objetos de foto de gatos são mantidos em um array. Ao percorrer cada item, você pode modificar os elementos do HTML.
First, declare an html variable with `let html = "";`.
Primeiro, declare uma variável html com `let html = "";`.
Then, loop through the JSON, adding HTML to the variable that wraps the key names in `strong` tags, followed by the value. When the loop is finished, you render it.
Em seguida, percorra o JSON por meio de um laço, adicionando HTML à variável que envolve os nomes das chaves em tags `strong`, seguidas pelo valor. Quando o laço estiver concluído, você o renderiza.
Here's the code that does this:
Aqui está o código para fazer isso:
```js
let html = "";
@ -30,13 +30,13 @@ json.forEach(function(val) {
});
```
**Note:** For this challenge, you need to add new HTML elements to the page, so you cannot rely on `textContent`. Instead, you need to use `innerHTML`, which can make a site vulnerable to cross-site scripting attacks.
**Observação:** para este desafio, você precisa adicionar novos elementos HTML à página. Por isso, você não pode confiar em `textContent`. Em vez disso, você precisa usar `innerHTML`, o que pode tornar um site vulnerável a ataques de scripts entre sites.
# --instructions--
Add a `forEach` method to loop over the JSON data and create the HTML elements to display it.
Adicione um método `forEach` para percorrer os dados do JSON e criar os elementos HTML para exibi-los.
Here is some example JSON:
Aqui está um exemplo de JSON:
```json
[
@ -52,19 +52,19 @@ Here is some example JSON:
# --hints--
Your code should store the data in the `html` variable
O código deve armazenar os dados na variável `html`
```js
assert(__helpers.removeWhiteSpace(code).match(/html(\+=|=html\+)/g))
```
Your code should use a `forEach` method to loop over the JSON data from the API.
O código deve usar um método `forEach` para percorrer os dados do JSON da API.
```js
assert(code.match(/json\.forEach/g));
```
Your code should wrap the key names in `strong` tags.
O código deve envolver os nomes das chaves em tags `strong`.
```js
assert(code.match(/<strong>.+<\/strong>/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7faf367417b2b2512be8
title: Get Geolocation Data to Find A User's GPS Coordinates
title: Obter dados de geolocalização para encontrar as coordenadas de GPS de um usuário
challengeType: 6
forumTopicId: 18188
dashedName: get-geolocation-data-to-find-a-users-gps-coordinates
@ -8,15 +8,15 @@ dashedName: get-geolocation-data-to-find-a-users-gps-coordinates
# --description--
Another cool thing you can do is access your user's current location. Every browser has a built in navigator that can give you this information.
Outra coisa legal que você consegue fazer é acessar a localização atual do usuário. Cada navegador tem um modo de navegação incorporado que pode dar a você esta informação.
The navigator will get the user's current longitude and latitude.
O modo de navegação obterá a longitude e a latitude atuais do usuário.
You will see a prompt to allow or block this site from knowing your current location. The challenge can be completed either way, as long as the code is correct.
Será solicitado que você permita ou evite que este site conheça sua localização atual. O desafio pode ser concluído das duas maneiras, desde que o código esteja correto.
By selecting allow, you will see the text on the output phone change to your latitude and longitude.
Ao selecionar que você permite, você verá o texto na saída do telefone mudar para sua latitude e longitude atuais.
Here's code that does this:
Aqui está o código para fazer isso:
```js
if (navigator.geolocation){
@ -26,33 +26,33 @@ if (navigator.geolocation){
}
```
First, it checks if the `navigator.geolocation` object exists. If it does, the `getCurrentPosition` method on that object is called, which initiates an asynchronous request for the user's position. If the request is successful, the callback function in the method runs. This function accesses the `position` object's values for latitude and longitude using dot notation and updates the HTML.
Primeiro, ele verifica se o objeto `navigator.geolocation` existe. Se existir, o método `getCurrentPosition` do objeto é chamado. Ele inicia uma solicitação asncrona da posição do usuário. Se a solicitação tiver sucesso, a função de callback do método é executada. Essa função acessa os valores do objeto `position` para latitude e longitude usando a notação de ponto e atualiza o HTML.
# --instructions--
Add the example code inside the `script` tags to check a user's current location and insert it into the HTML.
Adicione o código de exemplo entre as tags `script` para verificar a localização atual do usuário e coloque-o no HTML.
# --hints--
Your code should use `navigator.geolocation` to access the user's current location.
Seu código deve usar `navigator.geolocation` para acessar a localização atual do usuário.
```js
assert(code.match(/navigator\.geolocation\.getCurrentPosition/g));
```
Your code should use `position.coords.latitude` to display the user's latitudinal location.
Seu código deve usar `position.coords.latitude` para acessar a localização latitudinal do usuário.
```js
assert(code.match(/position\.coords\.latitude/g));
```
Your code should use `position.coords.longitude` to display the user's longitudinal location.
Seu código deve usar `position.coords.longitude` para acessar a localização longitudinal do usuário.
```js
assert(code.match(/position\.coords\.longitude/g));
```
You should display the user's position within the `div` element with `id="data"`.
Você deve exibir a posição do usuário dentro do elemento `div` com o `id="data"`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 5ccfad82bb2dc6c965a848e5
title: Get JSON with the JavaScript fetch method
title: Obter o JSON com o método fetch do JavaScript
challengeType: 6
forumTopicId: 301501
dashedName: get-json-with-the-javascript-fetch-method
@ -8,9 +8,9 @@ dashedName: get-json-with-the-javascript-fetch-method
# --description--
Another way to request external data is to use the JavaScript `fetch()` method. It is equivalent to `XMLHttpRequest`, but the syntax is considered easier to understand.
Outra maneira de solicitar dados externos é usar o método `fetch()` do JavaScript. Ele é equivalente ao método `XMLHttpRequest`, mas a sintaxe é considerada mais fácil de entender.
Here is the code for making a GET request to `/json/cats.json`
Aqui está o código para fazer uma solicitação de GET para `/json/cats.json`
```js
@ -22,29 +22,29 @@ fetch('/json/cats.json')
```
Take a look at each piece of this code.
Dê uma olhada em cada parte deste código.
The first line is the one that makes the request. So, `fetch(URL)` makes a `GET` request to the URL specified. The method returns a Promise.
A primeira linha é aquela que faz a solicitação. Então, `fetch(URL)` faz uma solicitação de `GET` para o URL especificado. O método retorna uma Promise.
After a Promise is returned, if the request was successful, the `then` method is executed, which takes the response and converts it to JSON format.
Após a devolução da promise, se a solicitação tiver sido bem-sucedida, o método `then` é executado, recebendo a resposta e convertendo-a para o formato JSON.
The `then` method also returns a Promise, which is handled by the next `then` method. The argument in the second `then` is the JSON object you are looking for!
O método `then` também retorna uma promise, que é tratada pelo próximo método `then`. O argumento no segundo `then` é o objeto do JSON que você está procurando!
Now, it selects the element that will receive the data by using `document.getElementById()`. Then it modifies the HTML code of the element by inserting a string created from the JSON object returned from the request.
Agora, ele seleciona o elemento que receberá os dados usando `document.getElementById()`. Em seguida, modifica o código HTML do elemento, inserindo uma string criada a partir do objeto do JSON retornado pela solicitação.
# --instructions--
Update the code to create and send a `GET` request to the freeCodeCamp Cat Photo API. But this time, using the `fetch` method instead of `XMLHttpRequest`.
Atualize o código para criar e enviar uma solicitação de `GET` para a API de fotos de gatos do freeCodeCamp. Desta vez, porém, use o método `fetch` em vez de `XMLHttpRequest`.
# --hints--
Your code should make a `GET` request with `fetch`.
O código deve fazer uma solicitação de `GET` com `fetch`.
```js
assert(code.match(/fetch\s*\(\s*('|")\/json\/cats\.json\1\s*\)/g));
```
Your code should use `then` to convert the response to JSON.
O código deve usar `then` para converter a resposta para JSON.
```js
assert(
@ -54,13 +54,13 @@ assert(
);
```
Your code should use `then` to handle the data converted to JSON by the other `then`.
O código deve usar `then` para lidar com os dados convertidos para JSON pelo outro `then`.
```js
assert(__helpers.removeWhiteSpace(code).match(/\.then\(\(?\w+\)?=>{[^}]*}\)/g));
```
Your code should get the element with id `message` and change its inner HTML to the string of JSON data.
O código deve obter o elemento com o id `message` e alterar seu HTML interno para a string de dados do JSON.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7fae367417b2b2512be3
title: Get JSON with the JavaScript XMLHttpRequest Method
title: Obter o JSON com o método XMLHttpRequest do JavaScript
challengeType: 6
forumTopicId: 301502
dashedName: get-json-with-the-javascript-xmlhttprequest-method
@ -8,19 +8,19 @@ dashedName: get-json-with-the-javascript-xmlhttprequest-method
# --description--
You can also request data from an external source. This is where APIs come into play.
Você também pode solicitar dados de uma fonte externa. Esse é o ponto em que as APIs entram no jogo.
Remember that APIs - or Application Programming Interfaces - are tools that computers use to communicate with one another. You'll learn how to update HTML with the data we get from APIs using a technology called AJAX.
Lembre-se de que as APIs - ou Interfaces de Programação de Aplicativos - são ferramentas que os computadores usam para se comunicarem uns com os outros. Você aprenderá como atualizar o HTML com os dados que recebemos das APIs usando uma tecnologia chamada AJAX.
Most web APIs transfer data in a format called JSON. JSON stands for JavaScript Object Notation.
A maioria das APIs da web transfere dados em um formato chamado JSON. JSON é uma abreviação de JavaScript Object Notation.
JSON syntax looks very similar to JavaScript object literal notation. JSON has object properties and their current values, sandwiched between a `{` and a `}`.
A sintaxe do JSON é bastante semelhante à notação de um literal de objeto do JavaScript. O JSON tem propriedades de objeto e seus valores atuais, envolvidos por um `{` e um `}`.
These properties and their values are often referred to as "key-value pairs".
Essas propriedades e seus valores são geralmente conhecidos como "pares chave-valor".
However, JSON transmitted by APIs are sent as `bytes`, and your application receives it as a `string`. These can be converted into JavaScript objects, but they are not JavaScript objects by default. The `JSON.parse` method parses the string and constructs the JavaScript object described by it.
Porém, o JSON transmitido pelas APIs é enviado como `bytes` e sua aplicação o recebe como uma `string`. Os JSON podem ser convertidos em objetos do JavaScript, mas não são objetos do JavaScript por padrão. O método `JSON.parse` analisa a string e constrói o objeto do JavaScript descrito por ela.
You can request the JSON from freeCodeCamp's Cat Photo API. Here's the code you can put in your click event to do this:
Você pode solicitar o JSON da API de fotos de gato do freeCodeCamp. Aqui está o código que você pode inserir no evento de clique para fazer isto:
```js
const req = new XMLHttpRequest();
@ -32,21 +32,21 @@ req.onload = function(){
};
```
Here's a review of what each piece is doing. The JavaScript `XMLHttpRequest` object has a number of properties and methods that are used to transfer data. First, an instance of the `XMLHttpRequest` object is created and saved in the `req` variable. Next, the `open` method initializes a request - this example is requesting data from an API, therefore is a `GET` request. The second argument for `open` is the URL of the API you are requesting data from. The third argument is a Boolean value where `true` makes it an asynchronous request. The `send` method sends the request. Finally, the `onload` event handler parses the returned data and applies the `JSON.stringify` method to convert the JavaScript object into a string. This string is then inserted as the message text.
Aqui está uma análise do que cada parte está fazendo. O objeto `XMLHttpRequest` do JavaScript tem uma série de propriedades e métodos que são usados para transferir dados. Primeiro, uma instância do objeto `XMLHttpRequest` é criada e salva na variável `req`. Em seguida, o método `open` inicia uma solicitação. Este exemplo está solicitando dados de uma API, portanto é uma solicitação `GET`. O segundo argumento para `open` é o URL da API de onde você está solicitando os dados. O terceiro argumento é um valor booleano, onde `true` torna a solicitação asncrona. O método `send` envia a solicitação. Por fim, o manipulador de eventos `onload` analisa os dados retornados e aplica o método `JSON.stringify` para converter o objeto do JavaScript em uma string. Essa string é, então, inserida como o texto da mensagem.
# --instructions--
Update the code to create and send a `GET` request to the freeCodeCamp Cat Photo API. Then click the `Get Message` button. Your AJAX function will replace the `The message will go here` text with the raw JSON output from the API.
Atualize o código para criar e enviar uma solicitação de `GET` para a API de fotos de gatos do freeCodeCamp. Em seguida, clique no botão `Get Message`. Sua função AJAX substituirá o texto `The message will go here` pela saída bruta do JSON da API.
# --hints--
Your code should create a new `XMLHttpRequest`.
O código deve criar uma nova `XMLHttpRequest`.
```js
assert(code.match(/new\s+?XMLHttpRequest\(\s*?\)/g));
```
Your code should use the `open` method to initialize a `GET` request to the freeCodeCamp Cat Photo API.
O código deve usar o método `open` para inicializar uma solicitação de `GET` para a API de fotos de gatos do freeCodeCamp.
```js
assert(
@ -56,13 +56,13 @@ assert(
);
```
Your code should use the `send` method to send the request.
O código deve usar o método `send` para enviar a solicitação.
```js
assert(code.match(/\.send\(\s*\)/g));
```
Your code should have an `onload` event handler set to a function.
O código deve ter um manipulador de evento `onload` definido para uma função.
```js
assert(
@ -70,13 +70,13 @@ assert(
);
```
Your code should use the `JSON.parse` method to parse the `responseText`.
O código deve usar o método `JSON.parse` para analisar o `responseText`.
```js
assert(code.match(/JSON\s*\.parse\(\s*.*\.responseText\s*\)/g));
```
Your code should get the element with class `message` and change its inner HTML to the string of JSON data.
O código deve obter o elemento com a classe `message` e alterar seu HTML interno para a string de dados do JSON.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7fad367417b2b2512be1
title: Handle Click Events with JavaScript using the onclick property
title: Tratar eventos de clique com o JavaScript usando a propriedade onclick
challengeType: 6
forumTopicId: 301503
dashedName: handle-click-events-with-javascript-using-the-onclick-property
@ -8,7 +8,7 @@ dashedName: handle-click-events-with-javascript-using-the-onclick-property
# --description--
You want your code to execute only once your page has finished loading. For that purpose, you can attach a JavaScript event to the document called `DOMContentLoaded`. Here's the code that does this:
Você quer que seu código execute apenas quando a página tenha terminado de carregar. Para isso, você pode incluir um evento JavaScript ao documento chamado `DOMContentLoaded`. Aqui está o código para fazer isso:
```js
document.addEventListener('DOMContentLoaded', function() {
@ -16,7 +16,7 @@ document.addEventListener('DOMContentLoaded', function() {
});
```
You can implement event handlers that go inside of the `DOMContentLoaded` function. You can implement an `onclick` event handler which triggers when the user clicks on the element with id `getMessage`, by adding the following code:
Você pode implementar manipuladores de eventos que vão dentro da função `DOMContentLoaded`. Você pode implementar um manipulador de evento `onclick` que dispara quando o usuário clica no elemento com id `getMessage`, adicionando o código a seguir:
```js
document.getElementById('getMessage').onclick = function(){};
@ -24,17 +24,17 @@ document.getElementById('getMessage').onclick = function(){};
# --instructions--
Add a click event handler inside of the `DOMContentLoaded` function for the element with id of `getMessage`.
Adicione um manipulador de eventos de clique em uma função `DOMContentLoaded` para o elemento com o id `getMessage`.
# --hints--
Your code should use the `document.getElementById` method to select the `getMessage` element.
O código deve usar o método `document.getElementById` para selecionar o elemento `getMessage`.
```js
assert(code.match(/document\s*\.getElementById\(\s*?('|")getMessage\1\s*?\)/g));
```
Your code should add an `onclick` event handler.
O código deve adicionar um manipulador de evento `onclick`.
```js
assert(typeof document.getElementById('getMessage').onclick === 'function');

View File

@ -1,6 +1,6 @@
---
id: 587d7faf367417b2b2512be9
title: Post Data with the JavaScript XMLHttpRequest Method
title: Publicar dados com o método XMLHttpRequest do JavaScript
challengeType: 6
forumTopicId: 301504
dashedName: post-data-with-the-javascript-xmlhttprequest-method
@ -8,9 +8,9 @@ dashedName: post-data-with-the-javascript-xmlhttprequest-method
# --description--
In the previous examples, you received data from an external resource. You can also send data to an external resource, as long as that resource supports AJAX requests and you know the URL.
Nos exemplos anteriores, você recebeu dados de um recurso externo. Você também pode enviar dados para um recurso externo, contanto que esse recurso suporte solicitações AJAX e que você conheça o URL.
JavaScript's `XMLHttpRequest` method is also used to post data to a server. Here's an example:
O método `XMLHttpRequest` do JavaScript também é usado para publicar dados em um servidor. Exemplo:
```js
const xhr = new XMLHttpRequest();
@ -26,27 +26,27 @@ const body = JSON.stringify({ userName: userName, suffix: ' loves cats!' });
xhr.send(body);
```
You've seen several of these methods before. Here the `open` method initializes the request as a `POST` to the given URL of the external resource, and uses the `true` Boolean to make it asynchronous. The `setRequestHeader` method sets the value of an HTTP request header, which contains information about the sender and the request. It must be called after the `open` method, but before the `send` method. The two parameters are the name of the header and the value to set as the body of that header. Next, the `onreadystatechange` event listener handles a change in the state of the request. A `readyState` of `4` means the operation is complete, and a `status` of `201` means it was a successful request. The document's HTML can be updated. Finally, the `send` method sends the request with the `body` value, which the `userName` key was given by the user in the `input` field.
Você já viu vários desses métodos antes. Aqui, o método `open` inicializa a solicitação como um `POST` para um determinado URL de um recurso externo, usando o booleano `true` para torná-lo asncrono. O método `setRequestHeader` define o valor de um cabeçalho de solicitação HTTP, que contém informações sobre o remetente e sobre a solicitação. Ele deve ser chamado após o método `open`, mas antes do método `send`. Os dois parâmetros são o nome do cabeçalho e o valor a ser definido como o corpo desse cabeçalho. Em seguida, o listener do evento `onreadystatechange` trata a mudança no estado da solicitação. Um `readyState` com o valor `4` significa que a operação foi concluída, enquanto o `status` `201` significa que a solicitação foi um sucesso. O HTML do documento pode ser atualizado. Por fim, o método `send` envia a solicitação com o valor de `body`, que era a chave `userName` fornecida pelo usuário no campo `input`.
# --instructions--
Update the code so it makes a `POST` request to the API endpoint. Then type your name in the input field and click `Send Message`. Your AJAX function should replace `Reply from Server will be here.` with data from the server. Format the response to display your name appended with the text `loves cats`.
Atualize o código para fazer uma solicitação de `POST` para o endpoint da API. Em seguida, digite seu nome no campo de entrada e clique em `Send Message`. Sua função do AJAX deve substituir `Reply from Server will be here.` pelos dados do servidor. Formate a resposta para que ela exiba seu nome anexado ao texto `loves cats`.
# --hints--
Your code should create a new `XMLHttpRequest`.
O código deve criar uma nova `XMLHttpRequest`.
```js
assert(code.match(/new\s+?XMLHttpRequest\(\s*?\)/g));
```
Your code should use the `open` method to initialize a `POST` request to the server.
O código deve usar o método `open` para inicializar uma solicitação de `POST` para o servidor.
```js
assert(code.match(/\.open\(\s*?('|")POST\1\s*?,\s*?url\s*?,\s*?true\s*?\)/g));
```
Your code should use the `setRequestHeader` method.
O código deve usar o método `setRequestHeader`.
```js
assert(
@ -56,13 +56,13 @@ assert(
);
```
Your code should have an `onreadystatechange` event handler set to a function.
O código deve ter um manipulador de evento `onreadystatechange` definido para uma função.
```js
assert(code.match(/\.onreadystatechange\s*?=/g));
```
Your code should get the element with class `message` and change its `textContent` to `userName loves cats`
O código deve obter o elemento com a classe `message` e mudar seu `textContent` para `userName loves cats`
```js
assert(
@ -72,7 +72,7 @@ assert(
);
```
Your code should use the `send` method.
O código deve usar o método `send`.
```js
assert(code.match(/\.send\(\s*?body\s*?\)/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7fae367417b2b2512be7
title: Pre-filter JSON to Get the Data You Need
title: Pré-filtrar o JSON para obter os dados de que você precisa
challengeType: 6
forumTopicId: 18257
dashedName: pre-filter-json-to-get-the-data-you-need
@ -8,11 +8,11 @@ dashedName: pre-filter-json-to-get-the-data-you-need
# --description--
If you don't want to render every cat photo you get from the freeCodeCamp Cat Photo API, you can pre-filter the JSON before looping through it.
Se você não quiser renderizar todas as fotos de gatos que você obtém na API de fotos de gatos do freeCodeCamp, você pode pré-filtrar o JSON antes de percorrer todo ele.
Given that the JSON data is stored in an array, you can use the `filter` method to filter out the cat whose `id` key has a value of `1`.
Como os dados do JSON estão armazenados em um array, você pode usar o método `filter` para tirar da seleção os gatos que têm a chave `id` com o valor de `1`.
Here's the code to do this:
Aqui está o código para fazer isso:
```js
json = json.filter(function(val) {
@ -22,11 +22,11 @@ json = json.filter(function(val) {
# --instructions--
Add code to `filter` the json data to remove the cat with the `id` value of `1`.
Adicione código ao método `filter` para filtrar os dados do json e remover o gato que tem em seu `id` o valor `1`.
# --hints--
Your code should use the `filter` method.
Você deve usar o método `filter`.
```js
assert(code.match(/json\.filter/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7fae367417b2b2512be6
title: Render Images from Data Sources
title: Renderizar imagens de fontes de dados
challengeType: 6
forumTopicId: 18265
dashedName: render-images-from-data-sources
@ -8,11 +8,11 @@ dashedName: render-images-from-data-sources
# --description--
The last few challenges showed that each object in the JSON array contains an `imageLink` key with a value that is the URL of a cat's image.
Os últimos desafios mostraram que cada objeto no array do JSON continha uma chave `imageLink` com um valor, que é o URL de uma imagem de gato.
When you're looping through these objects, you can use this `imageLink` property to display this image in an `img` element.
Ao percorrer esses objetos, você pode usar essa propriedade `imageLink` para exibir essa imagem em um elemento `img`.
Here's the code that does this:
Aqui está o código para fazer isso:
```js
html += "<img src = '" + val.imageLink + "' " + "alt='" + val.altText + "'>";
@ -20,17 +20,17 @@ html += "<img src = '" + val.imageLink + "' " + "alt='" + val.altText + "'>";
# --instructions--
Add code to use the `imageLink` and `altText` properties in an `img` tag.
Adicione código para usar as propriedades `imageLink` e `altText` em uma tag `img`.
# --hints--
You should use the `imageLink` property to display the images.
Você deve usar a propriedade `imageLink` para exibir as imagens.
```js
assert(code.match(/val\.imageLink/g));
```
You should use the `altText` for the `alt` attribute values of the images.
Você deve usar o `altText` nos valores do atributo `alt` das imagens.
```js
assert(code.match(/val\.altText/g));