fix(curriculum): fix challenges for russian language

This commit is contained in:
Valeriy S
2019-08-28 16:26:13 +03:00
committed by mrugesh
parent a17c3c44aa
commit 12f65a6742
1418 changed files with 39634 additions and 19395 deletions

View File

@@ -2,23 +2,27 @@
id: 587d7fae367417b2b2512be4
title: Access the JSON Data from an API
challengeType: 6
videoUrl: ''
forumTopicId: 301499
localeTitle: Доступ к данным JSON из API
---
## Description
<section id="description"> В предыдущей задаче вы видели, как получить данные JSON от FreeCodeCamp Cat Photo API. Теперь вы более подробно рассмотрите возвращенные данные, чтобы лучше понять формат JSON. Вспомните некоторые обозначения в JavaScript: <blockquote> [] -&gt; Квадратные скобки представляют собой массив <br> {} -&gt; Кудрявые скобки представляют собой объект <br> &quot;&quot; -&gt; Двойные кавычки представляют собой строку. Они также используются для ключевых имен в JSON </blockquote> Понимание структуры данных, возвращаемых API, важно, поскольку оно влияет на то, как вы извлекаете нужные значения. Справа нажмите кнопку «Получить сообщение», чтобы загрузить JavaScript-код FreeCodeCamp Cat Photo API JSON в HTML. Первый и последний символы, которые вы видите в данных JSON, являются квадратными скобками <code>[ ]</code> . Это означает, что возвращаемые данные представляют собой массив. Второй символ в данных JSON - кудрявый <code>{</code> скобка, которая запускает объект. Посмотрев внимательно, вы увидите, что есть три отдельных объекта. Данные JSON представляют собой массив из трех объектов, каждый из которых содержит информацию о фотографии кота. Вы узнали ранее, что объекты содержат пары «ключ-значение», разделенные запятыми. Например, в примере «Кошка» первый объект имеет <code>&quot;id&quot;:0</code> где «id» - это ключ, а 0 - его соответствующее значение. Аналогично, есть ключи для «imageLink», «altText» и «codeNames». У каждого объекта фотокамеры есть такие же клавиши, но с разными значениями. Еще одна интересная пара «ключ-значение» в первом объекте - <code>&quot;codeNames&quot;:[&quot;Juggernaut&quot;,&quot;Mrs. Wallace&quot;,&quot;ButterCup&quot;]</code> . Здесь «codeNames» - это ключ, а его значение представляет собой массив из трех строк. Возможно иметь массивы объектов, а также ключ с массивом в качестве значения. Помните, как обращаться к данным в массивах и объектах. Массивы используют скобку для доступа к определенному индексу элемента. Для доступа к значению данного свойства объекты используют либо скобку, либо точечную нотацию. Вот пример, который печатает «altText» первой фотографии кота - обратите внимание, что проанализированные данные JSON в редакторе сохраняются в переменной <code>json</code> : <blockquote> console.log (JSON [0] .altText); <br> // Печатает «Белый кот в зеленой шляпе в форме дыни на голове». </blockquote></section>
<section id='description'>
В предыдущей задаче вы видели, как получить данные JSON от FreeCodeCamp Cat Photo API. Теперь вы более подробно рассмотрите возвращенные данные, чтобы лучше понять формат JSON. Вспомните некоторые обозначения в JavaScript: <blockquote> [] -&gt; Квадратные скобки представляют собой массив <br> {} -&gt; Кудрявые скобки представляют собой объект <br> &quot;&quot; -&gt; Двойные кавычки представляют собой строку. Они также используются для ключевых имен в JSON </blockquote> Понимание структуры данных, возвращаемых API, важно, поскольку оно влияет на то, как вы извлекаете нужные значения. Справа нажмите кнопку «Получить сообщение», чтобы загрузить JavaScript-код FreeCodeCamp Cat Photo API JSON в HTML. Первый и последний символы, которые вы видите в данных JSON, являются квадратными скобками <code>[ ]</code> . Это означает, что возвращаемые данные представляют собой массив. Второй символ в данных JSON - кудрявый <code>{</code> скобка, которая запускает объект. Посмотрев внимательно, вы увидите, что есть три отдельных объекта. Данные JSON представляют собой массив из трех объектов, каждый из которых содержит информацию о фотографии кота. Вы узнали ранее, что объекты содержат пары «ключ-значение», разделенные запятыми. Например, в примере «Кошка» первый объект имеет <code>&quot;id&quot;:0</code> где «id» - это ключ, а 0 - его соответствующее значение. Аналогично, есть ключи для «imageLink», «altText» и «codeNames». У каждого объекта фотокамеры есть такие же клавиши, но с разными значениями. Еще одна интересная пара «ключ-значение» в первом объекте - <code>&quot;codeNames&quot;:[&quot;Juggernaut&quot;,&quot;Mrs. Wallace&quot;,&quot;ButterCup&quot;]</code> . Здесь «codeNames» - это ключ, а его значение представляет собой массив из трех строк. Возможно иметь массивы объектов, а также ключ с массивом в качестве значения. Помните, как обращаться к данным в массивах и объектах. Массивы используют скобку для доступа к определенному индексу элемента. Для доступа к значению данного свойства объекты используют либо скобку, либо точечную нотацию. Вот пример, который печатает «altText» первой фотографии кота - обратите внимание, что проанализированные данные JSON в редакторе сохраняются в переменной <code>json</code> : <blockquote> console.log (JSON [0] .altText); <br> // Печатает «Белый кот в зеленой шляпе в форме дыни на голове». </blockquote>
</section>
## Instructions
<section id="instructions"> Для кошки с «id» из 2, напечатайте на консоли второе значение в массиве <code>codeNames</code> . Чтобы получить доступ к значению, вы должны использовать скобки и точечную нотацию на объекте (который сохраняется в переменной <code>json</code> ). </section>
<section id='instructions'>
Для кошки с «id» из 2, напечатайте на консоли второе значение в массиве <code>codeNames</code> . Чтобы получить доступ к значению, вы должны использовать скобки и точечную нотацию на объекте (который сохраняется в переменной <code>json</code> ).
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Ваш код должен использовать скобки и точечные обозначения для доступа к правильному кодовому имени и распечатать «Loki» на консоли.
testString: 'assert(code.match(/(?:json\[2\]\.codeNames\[1\]|json\[2\]\[("|")codeNames\1\]\[1\])/g), "Your code should use bracket and dot notation to access the proper code name, and print "Loki" to the console.");'
- text: Your code should use bracket and dot notation to access the proper code name, and print "Loki" to the console.
testString: assert(code.match(/(?:json\[2\]\.codeNames\[1\]|json\[2\]\[('|")codeNames\1\]\[1\])/g));
```
@@ -87,14 +91,13 @@ tests:
</div>
</section>
## Solution
<section id='solution'>
```js
```html
// solution required
```
</section>

View File

@@ -2,23 +2,27 @@
id: 587d7fad367417b2b2512be2
title: Change Text with click Events
challengeType: 6
videoUrl: ''
forumTopicId: 301500
localeTitle: Изменить текст с помощью кнопки «События»
---
## Description
<section id="description"> Когда происходит событие клика, вы можете использовать JavaScript для обновления элемента HTML. Например, когда пользователь нажимает кнопку «Получить сообщение», он меняет текст элемента с <code>message</code> класса, чтобы сказать «Вот сообщение». Это работает, добавив следующий код в событие click: <code>document.getElementsByClassName(&#39;message&#39;)[0].textContent=&quot;Here is the message&quot;;</code> </section>
<section id='description'>
Когда происходит событие клика, вы можете использовать JavaScript для обновления элемента HTML. Например, когда пользователь нажимает кнопку «Получить сообщение», он меняет текст элемента с <code>message</code> класса, чтобы сказать «Вот сообщение». Это работает, добавив следующий код в событие click: <code>document.getElementsByClassName(&#39;message&#39;)[0].textContent=&quot;Here is the message&quot;;</code>
</section>
## Instructions
<section id="instructions"> Добавьте код внутри обработчика события <code>onclick</code> чтобы изменить текст внутри элемента <code>message</code> чтобы сказать «Вот сообщение». </section>
<section id='instructions'>
Добавьте код внутри обработчика события <code>onclick</code> чтобы изменить текст внутри элемента <code>message</code> чтобы сказать «Вот сообщение».
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Ваш код должен использовать метод <code>document.getElementsByClassName</code> чтобы выбрать элемент с <code>message</code> класса и установить его <code>textContent</code> в заданную строку.
testString: 'assert(code.match(/document\.getElementsByClassName\(\s*?("|")message\1\s*?\)\[0\]\.textContent\s*?=\s*?("|")Here is the message\2/g), "Your code should use the <code>document.getElementsByClassName</code> method to select the element with class <code>message</code> and set its <code>textContent</code> to the given string.");'
- text: Your code should use the <code>document.getElementsByClassName</code> method to select the element with class <code>message</code> and set its <code>textContent</code> to the given string.
testString: assert(code.match(/document\s*\.getElementsByClassName\(\s*?('|")message\1\s*?\)\[0\]\s*\.textContent\s*?=\s*?('|")Here is the message\2/g));
```
@@ -80,14 +84,13 @@ tests:
</div>
</section>
## Solution
<section id='solution'>
```js
```html
// solution required
```
</section>

View File

@@ -2,27 +2,45 @@
id: 587d7fae367417b2b2512be5
title: Convert JSON Data to HTML
challengeType: 6
videoUrl: ''
forumTopicId: 16807
localeTitle: Преобразование данных JSON в HTML
---
## Description
<section id="description"> Теперь, когда вы получаете данные из JSON API, вы можете отобразить его в HTML. Вы можете использовать метод <code>forEach</code> для циклического прохождения данных, поскольку объекты фотографии cat хранятся в массиве. По мере перехода к каждому элементу вы можете изменить элементы HTML. Сначала объявите html-переменную с <code>var html = &quot;&quot;;</code> , Затем прокрутите JSON, добавив HTML к переменной, которая обертывает имена ключей в <code>strong</code> тегах, а затем значение. Когда цикл закончен, вы его визуализируете. Вот код, который делает это: <blockquote> json.forEach (function (val) { <br> var keys = Object.keys (val); <br> html + = &quot;&lt;div class = &#39;cat&#39;&gt;&quot;; <br> keys.forEach (функция (ключ) { <br> html + = &quot;&lt;strong&gt;&quot; + ключ + &quot;&lt;/ strong&gt;:&quot; + val [key] + &quot;&lt;br&gt;&quot;; <br> }); <br> html + = &quot;&lt;/ div&gt; &lt;br&gt;&quot;; <br> }); </blockquote></section>
<section id='description'>
Теперь, когда вы получаете данные из JSON API, вы можете отобразить его в HTML. Вы можете использовать метод <code>forEach</code> для циклического прохождения данных, поскольку объекты фотографии cat хранятся в массиве. По мере перехода к каждому элементу вы можете изменить элементы HTML. Сначала объявите html-переменную с <code>var html = &quot;&quot;;</code> , Затем прокрутите JSON, добавив HTML к переменной, которая обертывает имена ключей в <code>strong</code> тегах, а затем значение. Когда цикл закончен, вы его визуализируете. Вот код, который делает это: <blockquote> json.forEach (function (val) { <br> var keys = Object.keys (val); <br> html + = &quot;&lt;div class = &#39;cat&#39;&gt;&quot;; <br> keys.forEach (функция (ключ) { <br> html + = &quot;&lt;strong&gt;&quot; + ключ + &quot;&lt;/ strong&gt;:&quot; + val [key] + &quot;&lt;br&gt;&quot;; <br> }); <br> html + = &quot;&lt;/ div&gt; &lt;br&gt;&quot;; <br> }); </blockquote>
</section>
## Instructions
undefined
<section id='instructions'>
Add a <code>forEach</code> method to loop over the JSON data and create the HTML elements to display it.
Here is some example JSON
```json
[
{
"id":0,
"imageLink":"https://s3.amazonaws.com/freecodecamp/funny-cat.jpg",
"altText":"A white cat wearing a green helmet shaped melon on its head. ",
"codeNames":[ "Juggernaut", "Mrs. Wallace", "Buttercup"
]
}
]
```
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Ваш код должен хранить данные в переменной <code>html</code>
testString: 'assert(code.match(/html\s+?(\+=|=\shtml\s\+)/g), "Your code should store the data in the <code>html</code> variable");'
- text: Ваш код должен использовать метод <code>forEach</code> для обработки данных JSON из API.
testString: 'assert(code.match(/json\.forEach/g), "Your code should use a <code>forEach</code> method to loop over the JSON data from the API.");'
- text: Ваш код должен обернуть имена ключевых слов <code>strong</code> тегами.
testString: 'assert(code.match(/<strong>.+<\/strong>/g), "Your code should wrap the key names in <code>strong</code> tags.");'
- text: Your code should store the data in the <code>html</code> variable
testString: assert(code.match(/html\s+?(\+=|=\shtml\s\+)/g));
- text: Your code should use a <code>forEach</code> method to loop over the JSON data from the API.
testString: assert(code.match(/json\.forEach/g));
- text: Your code should wrap the key names in <code>strong</code> tags.
testString: assert(code.match(/<strong>.+<\/strong>/g));
```
@@ -93,14 +111,13 @@ tests:
</div>
</section>
## Solution
<section id='solution'>
```js
```html
// solution required
```
</section>

View File

@@ -2,29 +2,33 @@
id: 587d7faf367417b2b2512be8
title: Get Geolocation Data to Find A User's GPS Coordinates
challengeType: 6
videoUrl: ''
localeTitle: 'Получите данные геолокации, чтобы найти GPS-координаты пользователя'
forumTopicId: 18188
localeTitle: Получите данные геолокации, чтобы найти GPS-координаты пользователя
---
## Description
<section id="description"> Еще одна интересная вещь, которую вы можете сделать, - это доступ к текущему местоположению вашего пользователя. Каждый браузер имеет встроенный навигатор, который может предоставить вам эту информацию. Навигатор получит текущую долготу и широту пользователя. Вы увидите приглашение разрешить или заблокировать этот сайт, зная ваше текущее местоположение. Задача может быть завершена в любом случае, если код верен. Выбрав allow, вы увидите, что текст на выходном телефоне изменится на широту и долготу. Вот код, который делает это: <blockquote> if (navigator.geolocation) { <br> navigator.geolocation.getCurrentPosition (функция (позиция) { <br> document.getElementById (&#39;data&#39;). innerHTML = &quot;широта:&quot; + position.coords.latitude + &quot;&lt;br&gt; долгота:&quot; + position.coords.longitude; <br> }); <br> } </blockquote> Во-первых, он проверяет <code>navigator.geolocation</code> объекта <code>navigator.geolocation</code> . Если это так, <code>getCurrentPosition</code> метод <code>getCurrentPosition</code> для этого объекта, который инициирует асинхронный запрос для позиции пользователя. Если запрос выполнен успешно, выполняется функция обратного вызова в методе. Эта функция осуществляет доступ к значениям объекта <code>position</code> для широты и долготы с использованием точечной нотации и обновляет HTML. </section>
<section id='description'>
Еще одна интересная вещь, которую вы можете сделать, - это доступ к текущему местоположению вашего пользователя. Каждый браузер имеет встроенный навигатор, который может предоставить вам эту информацию. Навигатор получит текущую долготу и широту пользователя. Вы увидите приглашение разрешить или заблокировать этот сайт, зная ваше текущее местоположение. Задача может быть завершена в любом случае, если код верен. Выбрав allow, вы увидите, что текст на выходном телефоне изменится на широту и долготу. Вот код, который делает это: <blockquote> if (navigator.geolocation) { <br> navigator.geolocation.getCurrentPosition (функция (позиция) { <br> document.getElementById (&#39;data&#39;). innerHTML = &quot;широта:&quot; + position.coords.latitude + &quot;&lt;br&gt; долгота:&quot; + position.coords.longitude; <br> }); <br> } </blockquote> Во-первых, он проверяет <code>navigator.geolocation</code> объекта <code>navigator.geolocation</code> . Если это так, <code>getCurrentPosition</code> метод <code>getCurrentPosition</code> для этого объекта, который инициирует асинхронный запрос для позиции пользователя. Если запрос выполнен успешно, выполняется функция обратного вызова в методе. Эта функция осуществляет доступ к значениям объекта <code>position</code> для широты и долготы с использованием точечной нотации и обновляет HTML.
</section>
## Instructions
undefined
<section id='instructions'>
Add the example code inside the <code>script</code> tags to check a user's current location and insert it into the HTML.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: ''
testString: 'assert(code.match(/navigator\.geolocation\.getCurrentPosition/g), "Your code should use <code>navigator.geolocation</code> to access the user&#39;s current location.");'
- text: ''
testString: 'assert(code.match(/position\.coords\.latitude/g), "Your code should use <code>position.coords.latitude</code> to display the user&#39;s latitudinal location.");'
- text: ''
testString: 'assert(code.match(/position\.coords\.longitude/g), "Your code should use <code>position.coords.longitude</code> to display the user&#39;s longitudinal location.");'
- text: ''
testString: 'assert(code.match(/document\.getElementById\(\s*?("|")data\1\s*?\)\.innerHTML/g), "You should display the user&#39;s position within the <code>data</code> div element.");'
- text: Your code should use <code>navigator.geolocation</code> to access the user&#39;s current location.
testString: assert(code.match(/navigator\.geolocation\.getCurrentPosition/g));
- text: Your code should use <code>position.coords.latitude</code> to display the user&#39;s latitudinal location.
testString: assert(code.match(/position\.coords\.latitude/g));
- text: Your code should use <code>position.coords.longitude</code> to display the user&#39;s longitudinal location.
testString: assert(code.match(/position\.coords\.longitude/g));
- text: You should display the user&#39;s position within the <code>data</code> div element.
testString: assert(code.match(/document\.getElementById\(\s*?('|")data\1\s*?\)\.innerHTML/g));
```
@@ -51,14 +55,13 @@ tests:
</div>
</section>
## Solution
<section id='solution'>
```js
```html
// solution required
```
</section>

View File

@@ -2,33 +2,57 @@
id: 587d7fae367417b2b2512be3
title: Get JSON with the JavaScript XMLHttpRequest Method
challengeType: 6
videoUrl: ''
forumTopicId: 301502
localeTitle: Получить JSON с помощью метода XMLHttpRequest JavaScript
---
## Description
undefined
<section id='description'>
You can also request data from an external source. This is where APIs come into play.
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.
Most web APIs transfer data in a format called JSON. JSON stands for JavaScript Object Notation.
JSON syntax looks very similar to JavaScript object literal notation. JSON has object properties and their current values, sandwiched between a <code>{</code> and a <code>}</code>.
These properties and their values are often referred to as "key-value pairs".
However, JSON transmitted by APIs are sent as <code>bytes</code>, and your application receives it as a <code>string</code>. These can be converted into JavaScript objects, but they are not JavaScript objects by default. The <code>JSON.parse</code> method parses the string and constructs the JavaScript object described by it.
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:
```js
req=new XMLHttpRequest();
req.open("GET",'/json/cats.json',true);
req.send();
req.onload=function(){
json=JSON.parse(req.responseText);
document.getElementsByClassName('message')[0].innerHTML=JSON.stringify(json);
};
```
Here's a review of what each piece is doing. The JavaScript <code>XMLHttpRequest</code> object has a number of properties and methods that are used to transfer data. First, an instance of the <code>XMLHttpRequest</code> object is created and saved in the <code>req</code> variable.
Next, the <code>open</code> method initializes a request - this example is requesting data from an API, therefore is a "GET" request. The second argument for <code>open</code> is the URL of the API you are requesting data from. The third argument is a Boolean value where <code>true</code> makes it an asynchronous request.
The <code>send</code> method sends the request. Finally, the <code>onload</code> event handler parses the returned data and applies the <code>JSON.stringify</code> method to convert the JavaScript object into a string. This string is then inserted as the message text.
</section>
## Instructions
<section id="instructions"> Обновите код для создания и отправки запроса «GET» в FreeCodeCamp Cat Photo API. Затем нажмите кнопку «Получить сообщение». Функция AJAX заменит текст «Сообщение будет здесь» с исходным выходом JSON из API. </section>
<section id='instructions'>
Обновите код для создания и отправки запроса «GET» в FreeCodeCamp Cat Photo API. Затем нажмите кнопку «Получить сообщение». Функция AJAX заменит текст «Сообщение будет здесь» с исходным выходом JSON из API.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: ''
testString: 'assert(code.match(/new\s+?XMLHttpRequest\(\s*?\)/g), "Your code should create a new <code>XMLHttpRequest</code>.");'
- text: Ваш код должен использовать <code>open</code> метод для инициализации запроса «GET» в FreeCodeCamp Cat Photo API.
testString: 'assert(code.match(/\.open\(\s*?("|")GET\1\s*?,\s*?("|")\/json\/cats\.json\2\s*?,\s*?true\s*?\)/g), "Your code should use the <code>open</code> method to initialize a "GET" request to the freeCodeCamp Cat Photo API.");'
- text: ''
testString: 'assert(code.match(/\.send\(\s*\)/g), "Your code should use the <code>send</code> method to send the request.");'
- text: В вашем коде должен быть обработчик события <code>onload</code> установленный на функцию.
testString: 'assert(code.match(/\.onload\s*=\s*function\(\s*?\)\s*?{/g), "Your code should have an <code>onload</code> event handler set to a function.");'
- text: ''
testString: 'assert(code.match(/JSON\.parse\(.*\.responseText\)/g), "Your code should use the <code>JSON.parse</code> method to parse the <code>responseText</code>.");'
- text: Ваш код должен получить элемент с <code>message</code> класса и изменить его внутренний HTML на строку данных JSON.
testString: 'assert(code.match(/document\.getElementsByClassName\(\s*?("|")message\1\s*?\)\[0\]\.innerHTML\s*?=\s*?JSON\.stringify\(.+?\)/g), "Your code should get the element with class <code>message</code> and change its inner HTML to the string of JSON data.");'
- text: Your code should create a new <code>XMLHttpRequest</code>.
testString: assert(code.match(/new\s+?XMLHttpRequest\(\s*?\)/g));
- text: Your code should use the <code>open</code> method to initialize a "GET" request to the freeCodeCamp Cat Photo API.
testString: assert(code.match(/\.open\(\s*?('|")GET\1\s*?,\s*?('|")\/json\/cats\.json\2\s*?,\s*?true\s*?\)/g));
- text: Your code should use the <code>send</code> method to send the request.
testString: assert(code.match(/\.send\(\s*\)/g));
- text: Your code should have an <code>onload</code> event handler set to a function.
testString: assert(code.match(/\.onload\s*=\s*(function|\(\s*?\))\s*?(\(\s*?\)|\=\>)\s*?{/g));
- text: Your code should use the <code>JSON.parse</code> method to parse the <code>responseText</code>.
testString: assert(code.match(/JSON\s*\.parse\(.*\.responseText\)/g));
- text: Your code should get the element with class <code>message</code> and change its inner HTML to the string of JSON data.
testString: assert(code.match(/document\s*\.getElementsByClassName\(\s*?('|")message\1\s*?\)\[0\]\s*\.innerHTML\s*?=\s*?JSON\.stringify\(.+?\)/g));
```
@@ -90,14 +114,61 @@ tests:
</div>
</section>
## Solution
<section id='solution'>
```js
```html
// solution required
<script>
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('getMessage').onclick=function(){
const req = new XMLHttpRequest();
req.open('GET', '/json/cats.json', true);
req.send();
req.onload = () => {
const json = JSON.parse(req.responseText);
document.getElementsByClassName('message')[0].innerHTML = JSON.stringify(json);
};
};
});
</script>
<style>
body {
text-align: center;
font-family: "Helvetica", sans-serif;
}
h1 {
font-size: 2em;
font-weight: bold;
}
.box {
border-radius: 5px;
background-color: #eee;
padding: 20px 5px;
}
button {
color: white;
background-color: #4791d0;
border-radius: 5px;
border: 1px solid #4791d0;
padding: 5px 10px 8px 10px;
}
button:hover {
background-color: #0F5897;
border: 1px solid #0F5897;
}
</style>
<h1>Cat Photo Finder</h1>
<p class="message">
The message will go here
</p>
<p>
<button id="getMessage">
Get Message
</button>
</p>
```
</section>

View File

@@ -2,25 +2,42 @@
id: 587d7fad367417b2b2512be1
title: Handle Click Events with JavaScript using the onclick property
challengeType: 6
videoUrl: ''
localeTitle: 'Ручка Нажмите «События» с помощью JavaScript, используя свойство onclick'
forumTopicId: 301503
localeTitle: Ручка Нажмите «События» с помощью JavaScript, используя свойство onclick
---
## Description
undefined
<section id='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 <code>DOMContentLoaded</code>. Here's the code that does this:
```js
document.addEventListener('DOMContentLoaded',function() {
});
```
You can implement event handlers that go inside of the <code>DOMContentLoaded</code> function. You can implement an <code>onclick</code> event handler which triggers when the user clicks on the element with id <code>getMessage</code>, by adding the following code:
```js
document.getElementById('getMessage').onclick=function(){};
```
</section>
## Instructions
undefined
<section id='instructions'>
Add a click event handler inside of the <code>DOMContentLoaded</code> function for the element with id of <code>getMessage</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: ''
testString: 'assert(code.match(/document\.getElementById\(\s*?("|")getMessage\1\s*?\)/g), "Your code should use the <code>document.getElementById</code> method to select the <code>getMessage</code> element.");'
- text: ''
testString: 'assert(typeof document.getElementById("getMessage").onclick === "function", "Your code should add an <code>onclick</code> event handler.");'
- text: Your code should use the <code>document.getElementById</code> method to select the <code>getMessage</code> element.
testString: assert(code.match(/document\s*\.getElementById\(\s*?('|")getMessage\1\s*?\)/g));
- text: Your code should add an <code>onclick</code> event handler.
testString: assert(typeof document.getElementById('getMessage').onclick === 'function');
```
@@ -80,14 +97,13 @@ tests:
</div>
</section>
## Solution
<section id='solution'>
```js
```html
// solution required
```
</section>

View File

@@ -2,33 +2,57 @@
id: 587d7faf367417b2b2512be9
title: Post Data with the JavaScript XMLHttpRequest Method
challengeType: 6
videoUrl: ''
forumTopicId: 301504
localeTitle: Опубликовать данные с помощью метода XMLHttpRequest JavaScript
---
## Description
undefined
<section id='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.
JavaScript's <code>XMLHttpRequest</code> method is also used to post data to a server. Here's an example:
```js
const xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 201){
const serverResponse = JSON.parse(xhr.response);
document.getElementsByClassName('message')[0].textContent = serverResponse.userName + serverResponse.suffix;
}
};
const body = JSON.stringify({ userName: userName, suffix: ' loves cats!' });
xhr.send(body);
```
You've seen several of these methods before. Here the <code>open</code> method initializes the request as a "POST" to the given URL of the external resource, and uses the <code>true</code> Boolean to make it asynchronous.
The <code>setRequestHeader</code> method sets the value of an HTTP request header, which contains information about the sender and the request. It must be called after the <code>open</code> method, but before the <code>send</code> method. The two parameters are the name of the header and the value to set as the body of that header.
Next, the <code>onreadystatechange</code> event listener handles a change in the state of the request. A <code>readyState</code> of 4 means the operation is complete, and a <code>status</code> of 201 means it was a successful request. The document's HTML can be updated.
Finally, the <code>send</code> method sends the request with the <code>body</code> value, which the <code>userName</code> key was given by the user in the <code>input</code> field.
</section>
## Instructions
undefined
<section id='instructions'>
Update the code to create and send a "POST" request. Then enter your name in input box and click "Send Message". Your AJAX function will replace "Reply from Server will be here." with the reply of the server. In this case, it is your name appended with " loves cats".
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: ''
testString: 'assert(code.match(/new\s+?XMLHttpRequest\(\s*?\)/g), "Your code should create a new <code>XMLHttpRequest</code>.");'
- text: ''
testString: 'assert(code.match(/\.open\(\s*?("|")POST\1\s*?,\s*?url\s*?,\s*?true\s*?\)/g), "Your code should use the <code>open</code> method to initialize a "POST" request to the server.");'
- text: ''
testString: 'assert(code.match(/\.setRequestHeader\(\s*?("|")Content-Type\1\s*?,\s*?("|")text\/plain\2\s*?\)/g), "Your code should use the <code>setRequestHeader</code> method.");'
- text: В вашем коде должен быть <code>onreadystatechange</code> события <code>onreadystatechange</code> установленный на функцию.
testString: 'assert(code.match(/\.onreadystatechange\s*?=/g), "Your code should have an <code>onreadystatechange</code> event handler set to a function.");'
- text: ''
testString: 'assert(code.match(/document\.getElementsByClassName\(\s*?("|")message\1\s*?\)\[0\]\.innerHTML\s*?=\s*?.+?\.responseText/g), "Your code should get the element with class <code>message</code> and change its inner HTML to the <code>responseText</code>.");'
- text: ''
testString: 'assert(code.match(/\.send\(\s*?userName\s*?\)/g), "Your code should use the <code>send</code> method.");'
- text: Your code should create a new <code>XMLHttpRequest</code>.
testString: assert(code.match(/new\s+?XMLHttpRequest\(\s*?\)/g));
- text: Your code should use the <code>open</code> method to initialize a "POST" request to the server.
testString: assert(code.match(/\.open\(\s*?('|")POST\1\s*?,\s*?url\s*?,\s*?true\s*?\)/g));
- text: Your code should use the <code>setRequestHeader</code> method.
testString: assert(code.match(/\.setRequestHeader\(\s*?('|")Content-Type\1\s*?,\s*?('|")application\/json;\s*charset=UTF-8\2\s*?\)/g));
- text: Your code should have an <code>onreadystatechange</code> event handler set to a function.
testString: assert(code.match(/\.onreadystatechange\s*?=/g));
- text: Your code should get the element with class <code>message</code> and change its <code>textContent</code> to "<code>userName</code> loves cats"
testString: assert(code.match(/document\.getElementsByClassName\(\s*?('|")message\1\s*?\)\[0\]\.textContent\s*?=\s*?.+?\.userName\s*?\+\s*?.+?\.suffix/g));
- text: Your code should use the <code>send</code> method.
testString: assert(code.match(/\.send\(\s*?body\s*?\)/g));
```
@@ -41,10 +65,11 @@ tests:
```html
<script>
document.addEventListener('DOMContentLoaded',function(){
document.getElementById('sendMessage').onclick=function(){
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('sendMessage').onclick = function(){
var userName=document.getElementById('name').value;
var userName = document.getElementById('name').value;
var url = 'https://jsonplaceholder.typicode.com/posts';
// Add your code below this line
@@ -95,14 +120,13 @@ tests:
</div>
</section>
## Solution
<section id='solution'>
```js
```html
// solution required
```
</section>

View File

@@ -2,23 +2,27 @@
id: 587d7fae367417b2b2512be7
title: Pre-filter JSON to Get the Data You Need
challengeType: 6
videoUrl: ''
forumTopicId: 18257
localeTitle: Предварительный фильтр JSON для получения необходимых данных
---
## Description
<section id="description"> Если вы не хотите отображать каждую фотографию кота, которую вы получаете из FreeCodeCamp Cat Photo API, вы можете предварительно фильтровать JSON перед ее прокруткой. Учитывая , что данные JSON хранится в массиве, вы можете использовать <code>filter</code> метод , чтобы отфильтровать кошку, ключ «Идентификатор» имеет значение 1. Вот код , чтобы сделать это: <blockquote> json = json.filter (функция (val) { <br> return (val.id! == 1); <br> }); </blockquote></section>
<section id='description'>
Если вы не хотите отображать каждую фотографию кота, которую вы получаете из FreeCodeCamp Cat Photo API, вы можете предварительно фильтровать JSON перед ее прокруткой. Учитывая , что данные JSON хранится в массиве, вы можете использовать <code>filter</code> метод , чтобы отфильтровать кошку, ключ «Идентификатор» имеет значение 1. Вот код , чтобы сделать это: <blockquote> json = json.filter (функция (val) { <br> return (val.id! == 1); <br> }); </blockquote>
</section>
## Instructions
<section id="instructions"> Добавьте код, чтобы <code>filter</code> данные json, чтобы удалить кошку с «id» значением 1. </section>
<section id='instructions'>
Добавьте код, чтобы <code>filter</code> данные json, чтобы удалить кошку с «id» значением 1.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Ваш код должен использовать метод <code>filter</code> .
testString: 'assert(code.match(/json\.filter/g), "Your code should use the <code>filter</code> method.");'
- text: Your code should use the <code>filter</code> method.
testString: assert(code.match(/json\.filter/g));
```
@@ -95,14 +99,13 @@ tests:
</div>
</section>
## Solution
<section id='solution'>
```js
```html
// solution required
```
</section>

View File

@@ -2,23 +2,27 @@
id: 587d7fae367417b2b2512be6
title: Render Images from Data Sources
challengeType: 6
videoUrl: ''
forumTopicId: 18265
localeTitle: Отображение изображений из источников данных
---
## Description
<section id="description"> Последние несколько проблем показали, что каждый объект в массиве JSON содержит ключ <code>imageLink</code> со значением, которое является URL-адресом изображения кошки. Когда вы перебираете эти объекты, вы можете использовать это свойство <code>imageLink</code> для отображения этого изображения в элементе <code>img</code> . Вот код, который делает это: <code>html += &quot;&lt;img src = &#39;&quot; + val.imageLink + &quot;&#39; &quot; + &quot;alt=&#39;&quot; + val.altText + &quot;&#39;&gt;&quot;;</code> </section>
<section id='description'>
Последние несколько проблем показали, что каждый объект в массиве JSON содержит ключ <code>imageLink</code> со значением, которое является URL-адресом изображения кошки. Когда вы перебираете эти объекты, вы можете использовать это свойство <code>imageLink</code> для отображения этого изображения в элементе <code>img</code> . Вот код, который делает это: <code>html += &quot;&lt;img src = &#39;&quot; + val.imageLink + &quot;&#39; &quot; + &quot;alt=&#39;&quot; + val.altText + &quot;&#39;&gt;&quot;;</code>
</section>
## Instructions
<section id="instructions"> Добавьте код, чтобы использовать свойства <code>imageLink</code> и <code>altText</code> в теге <code>img</code> . </section>
<section id='instructions'>
Добавьте код, чтобы использовать свойства <code>imageLink</code> и <code>altText</code> в теге <code>img</code> .
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Вы должны использовать свойство <code>imageLink</code> для отображения изображений.
testString: 'assert(code.match(/val\.imageLink/g), "You should use the <code>imageLink</code> property to display the images.");'
- text: You should use the <code>imageLink</code> property to display the images.
testString: assert(code.match(/val\.imageLink/g));
```
@@ -92,14 +96,13 @@ tests:
</div>
</section>
## Solution
<section id='solution'>
```js
```html
// solution required
```
</section>