Ver Mensaje Individual
  #1 (permalink)  
Antiguo 11/10/2005, 20:01
Spyn_ET
 
Fecha de Ingreso: diciembre-2003
Mensajes: 218
Antigüedad: 20 años, 4 meses
Puntos: 0
Clase objAjax

Buenas, hace 2 dias q decidí meterme de lleno en el mundo del Ajax, y la verdad es q me gusta mucho. He estado trasteando un poco y me he echo una clase en php llamada <b>objAjax</b>, cuya unica función es la de generar un objeto XMLHttpRequest(); y hacer un poco mas amigable su funcionamiento en php.

Esta muy verde y me gustaria q le echarais un ojo, la destriparais y me comentarais q os parece y si le falta algo.

Repito q es muuuuy simple, pero a mi me sirve y quizas os pueda servir a vosotros.

ajax.php
Código PHP:
<?

class objAjax
{
    var 
$url;
    var 
$codigo ="";
    var 
$entrada "";
    var 
$salida "";
    var 
$formato 'GET';
    
        
/********************************************************/
    /*    Constructor                                            */
    /*        - $entrada     --> Parametro de entrada            */
    /*        - $salida     --> Donde colocamos los datos        */
    /*        - $url     --> Url de donde cargamos datos            */
    /*        - $formato     --> GET o POST                        */
    /********************************************************/
    
function objAjax($entrada$salida,$url,$formato 'GET')
    { 
        
$this->url $url;
        
$this->entrada $entrada;
        
$this->formato $formato;
        
$this->Carga($salida);
    }
    
/********************************************************/
    /*    CreaCabecera                                        */
    /********************************************************/
    
function CreaCabecera()
    {
        
$this->codigo "<script>";
        
$this->codigo .= "function createRequestObject()\n";
        
$this->codigo .= "{\n";
        
$this->codigo .= "var request_;\n";
        
$this->codigo .= "var browser = navigator.appName;\n";
        
$this->codigo .= "if(browser == \"Microsoft Internet Explorer\"){\n";
        
$this->codigo .= "request_ = new ActiveXObject(\"Microsoft.XMLHTTP\");\n";
        
$this->codigo .= "}else{\n";
        
$this->codigo .= "request_ = new XMLHttpRequest();\n";
        
$this->codigo .= "}\n";
        
$this->codigo .= "return request_;\n";
        
$this->codigo .= "}\n";
        
$this->codigo .= "var http = createRequestObject();\n";
        
$this->codigo .= "var url = '".$this->url."';\n";
    }

    
/********************************************************/
    /*    LeeDatos                                            */
    /********************************************************/
    
function LeeDatos()
    {
            
        if (
$this->formato == 'GET')
        {
            
$this->codigo .= "function getInfo(valor){\n";
            if (
$this->entrada != '')
                {
                
$this->codigo .= "valor = document.getElementById('".$this->entrada."').value;";
                
$this->codigo .= "    http.open('get', '".$this->url."?".$this->entrada."=' + valor);\n";
                }
            else
                
$this->codigo .= "    http.open('get', '".$this->url."' + valor);\n";
            
$this->codigo .= "    http.onreadystatechange = handleInfo;\n";
            
$this->codigo .= "    http.send(null);\n";
            
$this->codigo .= "}\n";
        }
        else
            {
            
$this->codigo .= "function getInfo(valor){\n";
            
$this->codigo .= "    http.open('POST', '".$this->url."',true);\n";
            
$this->codigo .= "    http.onreadystatechange = handleInfo;\n";
            
$this->codigo .= "    http.setRequestHeader(\"Content-Type\", \"application/x-www-form-urlencoded\");\n";
            if (
$this->entrada != '')
                {
                
$this->codigo .= "    valor = document.getElementById('".$this->entrada."').value;\n";
                
$this->codigo .= "    http.send('".$this->entrada."=' + valor);\n";
                }
            else
                
$this->codigo .= "    http.send(null);\n";
            
$this->codigo .= "}\n";
            }
    }
    
/********************************************************/
    /*    EscribeDatos                                        */
    /*        - $div     --> Donde volcamos los datos            */
    /********************************************************/
    
function EscribeDatos($div)
    {
        
/*Funcion q muestra el resultado*/
        
$this->codigo .= "function handleInfo(){\n";
        
$this->codigo .= "    if(http.readyState == 1){\n";
        
$this->codigo .= "        document.getElementById('".$div."').innerHTML = 'Me estoy cargando...';\n";
        
$this->codigo .= "    }\n";
        
$this->codigo .= "    if(http.readyState == 4){\n";
        
$this->codigo .= "        document.getElementById('".$div."').innerHTML = http.responseText;\n";
        
$this->codigo .= "    }\n";
        
$this->codigo .= "}\n";
    }

    
/********************************************************/
    /*    Carga                                                */
    /*        - $en     --> Donde volcamos los datos            */
    /********************************************************/
    
function Carga($en)
    {
        
$this->CreaCabecera();
        
$this->LeeDatos();
        
$this->EscribeDatos($en);
        
$this->codigo .= "</script>\n";
    }

    
/********************************************************/
    /*    Muestra                                                */
    /********************************************************/
    
function Muestra ()
    {
        return 
$this->codigo;
    }
}
index.php

Código PHP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Primera Pagina con Ajax</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style>
.tNum
{
background-color:#FFFFCC;
width:100%;
border-style:solid;
border-width:thin;
text-align:center;
}
th
{
background-color:#FFCC00;
color:#000000;
}
.tdArt:hover
{
background-color:#FF3300;
color:#FFFFFF;
}
#my_div
{
background-color:#99CCFF;
border-style:dotted;
border-width:thin;
}
</style>
<?
include("ajax.php");

//Variables
$x=0;
$cols 15;

//Creamos el objeto $http
// id --> Es la ENTRADA
// my_div --> Es la Salida
// datos.php --> Es la URL de donde sacamos los datos.
// GET --> Es el FORMATO en que pasamos los datos. (POST/GET)
$http = new objAjax('id',"my_div","datos.php",'GET');
echo 
$http->Muestra();

?>
</head>
<body>
Numero de noticia: <input onKeyup="getInfo()" id="id"/>
<hr/>
<div id="my_div">
Haz click sobre algun numero de arriba.
</div>
</body>
</html>
datos.php
Código PHP:
<?php
// Utilizo una clase para conectar y operar con la BD, el objeto es $db.
include("connect.php"); //conectamos a la BD

//Recogemos el ID;
$id = (isset($_GET['id']))?$_GET['id']:$_POST['id'];

//realizamos la consulta
$result $db->query("    SELECT * FROM tabla WHERE ID='".$id."'");

$row $db->fetch_assoc($result);
echo 
"<h2>Estamos viendo la noticia: ".$id."</h3><br/>";
?>
<table width="100%" border="1">
    <tr>
        <th colspan="2"><?=$row[0]?></th>
    </tr>
    <tr>
      <td width="26%"><?=$row[1]?></td>
      <td width="74%"><?=$row[2]?> </td>
  </tr>
    <tr>
      <td colspan="2"><?=$row[3]?>&nbsp;</td>
  </tr>
    
</table>
Espero vuestros comentarios. Un saludo.

Podeis verlo funcionando: aqui
__________________
SymbianForever
SymbianForever.com, todo sobre y para tu symbian
aNieto2K | Themes para WordPress
De todo un poco