Skip to content

Instantly share code, notes, and snippets.

@ismasan
Created March 1, 2013 17:28
Show Gist options
  • Select an option

  • Save ismasan/5066273 to your computer and use it in GitHub Desktop.

Select an option

Save ismasan/5066273 to your computer and use it in GitHub Desktop.
Ejemplo: traer productos Bootic vía API y listar en HTML.
<html>
<head>
<title>Api products</title>
<style type="text/css" media="screen">
#list {
list-style-type: none;
margin: 0;
padding: 0;
}
.product {
float: left;
}
.product .link {
display: block;
width: 200px;
height: 200px;
overflow: hidden;
position: relative;
}
.product .title {
position: absolute;
left: 10px;
bottom: 10px;
background: black;
color: white;
padding: 5px 10px;
}
</style>
</head>
<body>
<h1>Productos</h1>
<ul id="list">
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
var productsURL = "https://api.bootic.net/v1/products.json?access_token=c322fd51a1cad5b00da0bf560efff89c&shop_subdomains=jmorales";
// Si un producto no tiene imagen, muestra esta
var placeholder = 'http://placehold.it/200x200';
// Esta es la plantilla para cada producto
var template = '<li class="product">';
template += '<a class="link" href="">';
template += '<span class="title"></span>';
template += '<img src="" class="thumbnail" />';
template += '</a>';
template += '</li>';
// Esta función recibe cada producto en la lista, genera el HTML necesario y lo inserta en ul#list
function renderProduct(i, item) {
// crea HTML de producto a partir de template, suministra atributos de producto
var e = $(template)
.find('.link').attr('href', item._links.web.href).end()
.find('.title').text(item.title).end();
// inserta imagen o placeholder
if(item.image) {
e.find('.thumbnail').attr('src', item.image.sizes.small)
} else {
e.find('.thumbnail').attr('src', placeholder)
}
// Inserta HTML de producto en lista
e.appendTo('#list')
}
$(function () {
// Carga productos, itera e insertalos en lista #list
$.getJSON(productsURL, function (data) {
$.each(data._embedded.items, renderProduct)
})
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment