{
"name": "JSON APIs and Ajax",
"order": 10.5,
"time": "2h",
"challenges": [
{
"id": "bb000000000000000000001",
"title": "Trigger Click Events with jQuery",
"description": [
"In this section, we'll learn how to get data from APIs. APIs - or Application Programming Interfaces - are tools that computers use to communicate with one another.",
"We'll also learn how to update HTML with the data we get from these APIs using a technology called Ajax.",
"First, let's review what the $(document).ready()
function does. This function makes it so all code inside of it only runs once our page loads.",
"Let's make our \"Get Message\" button change the text of the element with the class message
.",
"Before we can do this, we need to implement a click event
inside of our $(document).ready()
function by adding this code:",
"$(\"#getMessage\").on(\"click\", function(){
",
"",
"});
"
],
"tests": [
"assert(code.match(/\\$\\s*?\\(\\s*?(?:'|\")\\#getMessage(?:'|\")\\s*?\\)\\s*?\\.on\\s*?\\(\\s*?(?:'|\")click(?:'|\")\\s*?\\,\\s*?function\\s*?\\(\\s*?\\)\\s*?\\{/gi), 'message: Bind the click event to the button with the ID of getMessage
');",
"assert(code.match(/\\n*?\\s*?\\}\\n*?\\s*?\\);/gi) && code.match(/\\n*?\\s*?\\}\\);/gi).length >= 2, 'message: Be sure to close your functions with });
');"
],
"challengeSeed": [
"fccss",
" $(document).ready(function() {",
" // Only change code below this line.",
" ",
" // Only change code above this line.",
" });",
"fcces",
"",
"",
"
$(document).ready()
. Esta función hace que todo el código dentro de ella se ejecute sólo hasta que nuestra página ha sido cargada.",
"Hagamos que nuestro botón \"Get message\" cambie el texto del elemento con clase message
.",
"Antes de poder hacer esto, tenemos que implementar un evento de pulsación
dentro de nuestra función $(document).ready()
, añadiendo este código:",
"$(\"#getMessage\").on(\"click\", function(){
",
"",
"});
"
]
},
{
"id": "bc000000000000000000001",
"title": "Change Text with Click Events",
"description": [
"When our click event happens, we can use Ajax to update an HTML element.",
"Let's make it so that when a user clicks the \"Get Message\" button, we change the text of the element with the class message
to say \"Here is the message\".",
"We can do this by adding the following code within our click event:",
" $(\".message\").html(\"Here is the message\");
"
],
"tests": [
"assert(code.match(/\\$\\s*?\\(\\s*?(?:'|\")\\.message(?:'|\")\\s*?\\)\\s*?\\.html\\s*?\\(\\s*?(?:'|\")Here\\sis\\sthe\\smessage(?:'|\")\\s*?\\);/gi), 'message: Clicking the \"Get Message\" button should give the element with the class message
the text \"Here is the message\".');"
],
"challengeSeed": [
"fccss",
" $(document).ready(function() {",
" $(\"#getMessage\").on(\"click\", function(){",
" // Only change code below this line.",
" ",
" // Only change code above this line.",
" });",
" });",
"fcces",
"",
"",
"message
cambie para decir \"Here is the message\".",
"Podemos hacerlo añadiendo el siguiente código dentro de nuestro evento de pulsación:",
" $(\".message\").html(\"Here is the message\");
"
]
},
{
"id": "bb000000000000000000002",
"title": "Get JSON with the jQuery getJSON Method",
"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.",
"Most web APIs transfer data in a format called JSON. JSON stands for JavaScript Object Notation.",
"You've already been using JSON whenever you create a JavaScript object. JSON is nothing more than object properties and their current values, sandwiched between a {
and a }
.",
"These properties and their values are often referred to as \"key-value pairs\".",
"Let's get the JSON from Free Code Camp's Cat Photo API.",
"Here's the code you can put in your click event to do this:",
" $.getJSON(\"/json/cats.json\", function(json) {
",
" $(\".message\").html(JSON.stringify(json));
",
" });
",
"Once you've added this, click the \"Get Message\" button. Your Ajax function will replace the \"The message will go here\" text with the raw JSON output from the Free Code Camp Cat Photo API."
],
"tests": [
"assert(code.match(/\\$\\s*?\\(\\s*?(\\\"|\\')\\#getMessage(\\\"|\\')\\s*?\\)\\s*?\\.\\s*?on\\s*?\\(\\s*?(\\\"|\\')click(\\\"|\\')\\s*?\\,\\s*?function\\s*?\\(\\s*?\\)\\s*?\\{/gi), 'message: You should have a click handler on the getMessage button to trigger the AJAX request.');",
"assert(code.match(/\\s*?\\}\\s*?\\)\\s*?\\;/gi), 'message: You should have at least one closing set of brackets and parenthesis.');",
"assert(code.match(/\\s*?\\}\\s*?\\)\\s*?\\;/gi) && code.match(/\\,\\s*?function\\s*?\\(\\s*?\\w*?\\s*?\\)\\s*?\\{/gi) && code.match(/\\s*?\\}\\s*?\\)\\s*?\\;/gi).length === code.match(/\\s*?function\\s*?\\(\\s*?\\w*?\\s*?\\)\\s*?\\{/gi).length, 'message: Each callback function should have a closing set of brackets and parenthesis.');",
"assert(code.match(/\\$\\s*?\\.\\s*?getJSON\\s*?\\(\\s*?(\\\"|\\')\\\/json\\\/cats\\.json(\\\"|\\')\\s*?\\,\\s*?function\\s*?\\(\\s*?json\\s*?\\)\\s*?\\{/gi), 'message: You should be making use of the getJSON method given in the description to load data from the json file.');",
"assert(code.match(/\\$\\s*?\\(\\s*?(\\\"|\\')\\.message(\\\"|\\')\\s*?\\)\\s*?\\.\\s*?html\\s*?\\(\\s*?JSON\\s*?\\.\\s*?stringify\\s*?\\(\\s*?json\\s*?\\)\\s*?\\)/gi), 'message: Don't forget to make the .html
change the contents of the message box so that it contains the result of the getJSON.');"
],
"challengeSeed": [
"fccss",
" $(document).ready(function() {",
"",
" $(\"#getMessage\").on(\"click\", function(){",
" // Only change code below this line.",
" ",
" ",
" ",
" // Only change code above this line.",
" });",
"",
" });",
"fcces",
"",
"{
y un }
. ",
"Estas propiedades y sus valores a menudo se denominan \" pares llave-valor\".",
"Vamos a obtener el JSON de la API de fotos de gato de Free Code Camp.",
"Aquí está el código que puedes poner en tu evento de pulsación para lograrlo:",
" $.getJSON(\"/json/cats.json\", function(json) {
",
" $(\".message\").html(JSON.stringify(json));
",
" });
",
"Una vez lo añadas, pulsa el botón \"Get Message\". Su función Ajax sustituirá el texto \"The message will go here\" con la salida JSON en bruto de la API de fotos de gato de Free Code Camp."
]
},
{
"id": "bb000000000000000000003",
"title": "Convert JSON Data to HTML",
"description": [
"Now that we're getting data from a JSON API, let's display it in our HTML.",
"We can use the .forEach()
method to loop through our data and modify our HTML elements.",
"First, let's declare an html variable with var html = \"\";
.",
"Then, let's loop through our JSON, adding more HTML to that variable. When the loop is finished, we'll render it.",
"Here's the code that does this:",
"json.forEach(function(val) {
",
" var keys = Object.keys(val);
",
" html += \"<div class = 'cat'>\";
",
" keys.forEach(function(key) {
",
" html += \"<b>\" + key + \"</b>: \" + val[key] + \"<br>\";
",
" });
",
" html += \"</div><br>\";
",
"});
"
],
"tests": [
"assert(code.match(/json\\.forEach/gi), 'message: The message box should have something in it.');"
],
"challengeSeed": [
"fccss",
" $(document).ready(function() {",
"",
" $(\"#getMessage\").on(\"click\", function() {",
" $.getJSON(\"/json/cats.json\", function(json) {",
"",
" var html = \"\";",
" // Only change code below this line.",
" ",
" ",
" ",
" // Only change code above this line.",
"",
" $(\".message\").html(html);",
"",
" });",
" });",
" });",
"fcces",
"",
".forEach()
para recorrer nuestros datos y modificar nuestros elementos HTML.",
"En primer lugar, vamos a declarar una variable llamada html
con var html = \"\";
.",
"Después, iteremos a traveś de nuestro JSON, añadiendo más HTML a esa variable. Cuando se termina el ciclo, vamos a presentarla. ",
"Aquí está el código que hace esto:",
"json.forEach(function(val) {
",
" var keys = Object.keys(val);
",
" html += \"<div class = 'cat'>\";
",
" keys.forEach(function(key) {
",
" html += \"<b>\" + key + \"</b>: \" + val[key] + \"<br>\";
",
" });
",
" html += \"</div><br>\";
",
"});
"
]
},
{
"id": "bb000000000000000000004",
"title": "Render Images from Data Sources",
"description": [
"We've seen from the last two lessons that each object in our JSON array contains an imageLink
key with a value that is the url of a cat's image.",
"When we're looping through these objects, let's use this imageLink
property to display this image in an img
element.",
"Here's the code that does this:",
" html += \"<img src = '\" + val.imageLink + \"'>\";
"
],
"tests": [
"assert(code.match(/val.imageLink/gi), 'message: You should have used the imageLink
property to display the images.');"
],
"challengeSeed": [
"fccss",
" $(document).ready(function() {",
"",
" $(\"#getMessage\").on(\"click\", function() {",
" $.getJSON(\"/json/cats.json\", function(json) {",
"",
" var html = \"\";",
"",
" json.forEach(function(val) {",
"",
" html += \"imageLink
con un valor que corresponde a la url de la imagen de un gato.",
"Cuando estamos recorriendo estos objetos, usemos esta propiedad imageLink
para visualizar la imagen en un elemento img
.",
"Aquí está el código que hace esto:",
" html += \"<img src = '\" + val.imageLink + \"'>\";
"
]
},
{
"id": "bb000000000000000000005",
"title": "Prefilter JSON",
"description": [
"If we don't want to render every cat photo we get from our Free Code Camp's Cat Photo JSON API, we can pre-filter the json before we loop through it.",
"Let's filter out the cat whose \"id\" key has a value of 1.",
"Here's the code to do this:",
"json = json.filter(function(val) {
",
" return(val.id !== 1);
",
"});
"
],
"tests": [
"assert(code.match(/filter/gi), 'message: You should be making use of the .filter method.');"
],
"challengeSeed": [
"fccss",
" $(document).ready(function() {",
"",
" $(\"#getMessage\").on(\"click\", function() {",
" $.getJSON(\"/json/cats.json\", function(json) {",
"",
" var html = \"\";",
"",
" // Only change code below this line.",
" ",
" ",
" ",
" // Only change code above this line.",
"",
" json.forEach(function(val) {",
"",
" html += \"json = json.filter(function(val) {
",
" return(val.id !== 1);
",
"});
"
]
},
{
"id": "bb000000000000000000006",
"title": "Get Geo-location Data",
"description": [
"Another cool thing we can do is access our user's current location. Every browser has a built in navigator that can give us this information.",
"The navigator will get our user's current longitude and latitude.",
"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.",
"By selecting allow you will see the text on the output phone change to your latitude and longitude",
"Here's some code that does this:",
"if (navigator.geolocation) {
",
" navigator.geolocation.getCurrentPosition(function(position) {
",
" $(\"#data\").html(\"latitude: \" + position.coords.latitude + \"<br>longitude: \" + position.coords.longitude);
",
" });
",
"}
"
],
"tests": [
"assert(code.match(/navigator\\.geolocation\\.getCurrentPosition/gi), 'message: You should make use of the navigator.geolocation
to access the users current location.');"
],
"challengeSeed": [
"fccss",
" // Only change code below this line.",
" ",
" ",
" ",
" // Only change code above this line.",
"fcces",
"if (navigator.geolocation) {
",
" navigator.geolocation.getCurrentPosition(function(position) {
",
" $(\"#data\").html(\"latitude: \" + position.coords.latitude + \"<br>longitude: \" + position.coords.longitude);
",
" });
",
"}
"
]
}
]
}