Simulador (Cuando presiona el botón "ejecutar el programa"
se graban todos los cuadros de texto y se ejecuta el primero de la lista
mostrando en una página el resultado)
Problema:
<html>
<head>
<title>Problema</title>
<script src="funciones.js" language="JavaScript"></script>
</head>
<body>
<h2>Recuperar datos del servidor almacenados en una base de datos en formato JSON utilizando la
librería JSON.php</h2>
<br>
Ingrese el código del artículo:
<input type="text" name="codigo" id="codigo" size="5"><br>
<input type="button" value="Recuperar" id="boton1">
<div id="resultados"></div>
</body>
</html>
addEvent(window,'load',inicializarEventos,false);
function inicializarEventos()
{
var ob=document.getElementById('boton1');
addEvent(ob,'click',presionBoton,false);
}
var conexion1;
function presionBoton(e)
{
conexion1=crearXMLHttpRequest();
conexion1.onreadystatechange = procesarEventos;
var codigo=document.getElementById('codigo').value;
conexion1.open('GET','pagina1.php?codigo='+codigo, true);
conexion1.send(null);
}
function procesarEventos()
{
var resultados = document.getElementById("resultados");
if(conexion1.readyState == 4)
{
alert('Cadena en formato JSON: '+conexion1.responseText);
var datos=eval("(" + conexion1.responseText + ")");
var salida='';
if (datos.length>0)
{
salida += 'Codigo:'+datos[0].codigo+"<br>";
salida += 'Descripcion:'+datos[0].descripcion+"<br>";
salida += 'Precio:'+datos[0].precio+"<br><br>";
}
else
salida='No existe ese codigo.';
resultados.innerHTML = salida;
}
else
{
resultados.innerHTML = "Cargando...";
}
}
//***************************************
//Funciones comunes a todos los problemas
//***************************************
function addEvent(elemento,nomevento,funcion,captura)
{
if (elemento.attachEvent)
{
elemento.attachEvent('on'+nomevento,funcion);
return true;
}
else
if (elemento.addEventListener)
{
elemento.addEventListener(nomevento,funcion,captura);
return true;
}
else
return false;
}
function crearXMLHttpRequest()
{
var xmlHttp=null;
if (window.ActiveXObject)
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
else
if (window.XMLHttpRequest)
xmlHttp = new XMLHttpRequest();
return xmlHttp;
}
<?php
$conexion=mysql_connect("localhost","root","z80") or die("Problemas en la conexion");
mysql_select_db("bdajax",$conexion) or die("Problemas en la seleccion
de la base de datos");
$registros=mysql_query("select codigo,descripcion,precio from perifericos where
codigo=$_REQUEST[codigo]",$conexion) or die("Problemas en el select".mysql_error());
if ($reg=mysql_fetch_array($registros))
{
$vec[]=$reg;
}
else
$vec='';
require('../JSON.php');
$json=new Services_JSON();
$cad=$json->encode($vec);
echo $cad;
?>