Foros aprenderaprogramar.com
Aprender a programar => Aprender a programar desde cero => Mensaje iniciado por: pedro,, en 23 de Marzo 2016, 22:42
-
Buenas.
Dejo una posible solución al ejercicio.
Considerando el siguiente archivo XML
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
</book>
</catalog>
a) Transforma el archivo xml para que id en lugar de ser un atributo de etiqueta sea una etiqueta
<?xml version="1.0"?>
<catalog>
<book>
<idBook>bk101</idBook>
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
</book>
<book>
<idBook>bk102</idBook>
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
</book>
<book>
<idBook>bk103</idBook>
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
</book>
</catalog>
b) Crea un archivo html que permita elegir el título (title) y dinámicamente recupere desde el archivo xml el contenido de todas las demás etiquetas incluido el id y los muestre por pantalla.
<!DOCTYPE html>
<html>
<head>
<title>Cursos aprende a programar</title>
<meta charset="utf-8">
<style type="text/css">
*{font-family:sans-serif;} a:link {text-decoration:none;} select{font-size:18px;}
#datosLibro {
font-size: 20px;
color: blue;
}
</style>
<script>
function mostrarDatosLibro(str) {
var libroElegido='';
if (str=='xmlDeveloper') {
libroElegido="XML Developer's Guide";
} else if(str=='midnightRain') {
libroElegido='Midnight Rain';
} else if(str=='maeveAscendat') {
libroElegido='Maeve Ascendant';
} else {
libroElegido='none';
}
var xmlhttp;
if (str.length == 0 || libroElegido == 'none') {
document.getElementById("txtInformacion").innerHTML = "no hay datos";
return;
}
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var xmlDoc = xmlhttp.responseXML;
librosRecibidos = xmlDoc.getElementsByTagName('book');
for (var i=0; i<librosRecibidos.length;i++) {
var nombreLibro = librosRecibidos[i].getElementsByTagName('title')[0].innerHTML;
if (nombreLibro == libroElegido) {
document.getElementById("txtInformacion").innerHTML = 'El libro recibido por get en segundo plano es ' + nombreLibro;
var msg = 'Titulo: ' + nombreLibro;
msg += '<br/>id: ' + librosRecibidos[i].getElementsByTagName('idBook')[0].innerHTML;
msg += '<br/>Autor: ' + librosRecibidos[i].getElementsByTagName('author')[0].innerHTML;
msg += '<br/>Precio: ' + librosRecibidos[i].getElementsByTagName('price')[0].innerHTML;
msg += '<br/>Fecha publicación: ' + librosRecibidos[i].getElementsByTagName('publish_date')[0].innerHTML;
document.getElementById('datosLibro').innerHTML = msg;
}
}
}
}
xmlhttp.open("GET","ejemplo.xml");
xmlhttp.send();
}
</script>
</head>
<body style="margin:20px;">
<h2>Elige un libro:</h2>
<form action="">
<select onchange="mostrarDatosLibro(this.value)">
<option value="none">Elige</option>
<option value="xmlDeveloper">XML Developer's Guide</option>
<option value="midnightRain">Midnight Rain</option>
<option value="maeveAscendat">Maeve Ascendant</option>
</select>
</form>
<br/>
<p>Informacion sobre operacion en segundo plano con Ajax: <span style="color:brown;" id="txtInformacion"></span></p>
<div id="datosLibro"> </div>
</body>
</html>
http://aprendehtml.byethost3.com/Ajax/CU01210F/ejercicioCU01210F_1.html
Saludos.
-
Hola Pedro el ejercicio está bien. Hay una cosa que quizás resultara interesante. La idea es que el libro tiene un id que en el xml has definido como idBook, como el id es un valor numérico se supone que único, podría ser interesante identificar el libro en base a ese id en lugar de en base al nombre del libro que es una cadena de texto donde podría ser más fácil que hubiera errores.
El cambio arrancaría aquí:
if (str=='xmlDeveloper') {
libroElegido="101";
} else if(str=='midnightRain') {
libroElegido='102';
} else if(str=='maeveAscendat') {
libroElegido='103';
} else {
libroElegido='none';
}
A partir de ahí habría que hacer algunos cambios más.
En realidad sería prácticamente igual pero usando el id para identificar el libro.
No lo he probado pero parece que sería una buena idea ya que la comparación de cadenas de texto tiende a ser más imprecisa (incluso podría presentarse un caso raro como dos libros con el mismo título)
Saludos
-
Hola Alex.
Dejo el código con la solución que propones, no ha habido que variar mucho:
<!DOCTYPE html>
<html>
<head>
<title>Cursos aprende a programar</title>
<meta charset="utf-8">
<style type="text/css">
*{font-family:sans-serif;} a:link {text-decoration:none;} select{font-size:18px;}
#datosLibro {
font-size: 20px;
color: blue;
}
</style>
<script>
function mostrarDatosLibro(str) {
var libroElegido='';
if (str=='xmlDeveloper') {
libroElegido=101;
} else if(str=='midnightRain') {
libroElegido=102;
} else if(str=='maeveAscendat') {
libroElegido=103;
} else {
libroElegido='none';
}
var xmlhttp;
if (str.length == 0 || libroElegido == 'none') {
document.getElementById("txtInformacion").innerHTML = "no hay datos";
return;
}
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var xmlDoc = xmlhttp.responseXML;
librosRecibidos = xmlDoc.getElementsByTagName('book');
for (var i=0; i<librosRecibidos.length;i++) {
var idLibro = librosRecibidos[i].getElementsByTagName('idBook')[0].innerHTML;
console.log(idLibro);
if (idLibro == libroElegido) {
document.getElementById("txtInformacion").innerHTML = 'El id del libro recibido por get en segundo plano es ' + idLibro;
var msg = 'id: ' + idLibro;
msg += '<br/>Título: ' + librosRecibidos[i].getElementsByTagName('title')[0].innerHTML;
msg += '<br/>Autor: ' + librosRecibidos[i].getElementsByTagName('author')[0].innerHTML;
msg += '<br/>Precio: ' + librosRecibidos[i].getElementsByTagName('price')[0].innerHTML;
msg += '<br/>Fecha publicación: ' + librosRecibidos[i].getElementsByTagName('publish_date')[0].innerHTML;
document.getElementById('datosLibro').innerHTML = msg;
}
}
}
}
xmlhttp.open("GET","ejemplo_b.xml");
xmlhttp.send();
}
</script>
</head>
<body style="margin:20px;">
<h2>Elige un libro:</h2>
<form action="">
<select onchange="mostrarDatosLibro(this.value)">
<option value="none">Elige</option>
<option value="xmlDeveloper">XML Developer's Guide</option>
<option value="midnightRain">Midnight Rain</option>
<option value="maeveAscendat">Maeve Ascendant</option>
</select>
</form>
<br/>
<p>Informacion sobre operacion en segundo plano con Ajax: <span style="color:brown;" id="txtInformacion"></span></p>
<div id="datosLibro"> </div>
</body>
</html>
Para esta solución en el archivo xml tuve que cambiar los id, porque allí aparecían como, bk101, bk102... Dejándolos sólo como valores numéricos, 101, 102, 103...
http://aprendehtml.byethost3.com/Ajax/CU01210F/ejercicioCU01210F_1_b.html
Gracias por la corrección y los comentarios.
Saludos.
-
Hola, con la variación que has hecho vemos una forma alternativa de trabajar, siempre es bueno ver alternativas. Gracias a tí por poner el código de la variación
Saludos