Ver Mensaje Individual
  #1 (permalink)  
Antiguo 30/01/2009, 10:35
diegoturriaga
 
Fecha de Ingreso: noviembre-2004
Ubicación: Buenos Aires
Mensajes: 34
Antigüedad: 19 años, 5 meses
Puntos: 0
Pregunta clase ajax (evento onStateChange)

Intento armar mi propia clase javascript para trabajar con AJAX y php lo más cómodamente posible sin depender de librerías de terceros... pero estoy dándome la cabeza una y otra vez contra la pared así que os dejo aquí el problema y el código en cuestión:

Problema: Básicamente (me parece) que el problema es que al momento de ejecutarse el evento onStateChange no se ve al objeto... (fuera del alcance) pero todo cuanto se me ocurrió sigue igual...
PD: sacar la objeto xmlHttpReq fuera de la clase no me parece una alternativa correcta para una clase :(aparte de que ya lo hice y tampoco me reconoce a la propiedad tipo)

<inicio de ajax.js>

// Especifica opciones para tipo respuesta
var tipo = { xml:0, texto:1, json:2 }

// Especifica opciones para el metodo de envio
var metodo = { get:"GET", post:"POST" }

Ajax.prototype.xmlHttpReq;
Ajax.prototype.sync;
Ajax.prototype.urlReceptor;
Ajax.prototype.funProcResp;
Ajax.prototype.funProcError;
Ajax.prototype.form;
Ajax.prototype.metodo;
Ajax.prototype.tipo;
Ajax.prototype.iniciado;
Ajax.prototype.cargarForm;
Ajax.prototype.enviarForm;
Ajax.prototype.enviar;

//constructor
function Ajax() {

// instancia de un objeto xmlHttpRequest
this.xmlHttpReq = instanciarXMLHTTPReq();

// transmisión sincrónica (true) o asincrónica (false: por defecto)
this.sync = false;

// url de la página que recibirá y procesará la información
this.urlReceptor = '';

// función javascript que procesará la respuesta del receptor
this.funProcResp = null;

// funcion javascript que procesará el posible error que se genere
this.funProcError = null;

// propiedad form: contiene los datos de un formulario
this.form = '';

// propiedad metodo: define el metodo de envio (metodo.post, metodo.get)
this.metodo = metodo.post;

// propiedad tipo: esablece el tipo de respuesta (tipo.texto, tipo.xml)
this.tipo = tipo.texto;

// método que devuelve true si se pudo instanciar al objeto XMLHTTPReq
this.iniciado = function() {
return (this.xmlHttpReq!=null);
}

// método que prepara los datos de un formulario para porder enviarlos
// opcionalmente puede no enviar los campos de tipo password
this.cargarForm = function(form) {
this.form = '';
var filtrarPasswords = (arguments[1] ? arguments[1] : false);
for (e=0;e<form.elements.length;e++) {
if (!filtrarPasswords || form.elements[e].type != 'password') {
var name = form.elements[e].name;
if (name!='') {
this.form += (this.form=='')?'':'&';
this.form += name+'='+escape(form.elements[e].value);
}
}
}
}

// método que envía un formulario usando el método get
// opcionalmente recibe, en orden: urlReceptor, metodo, sync, form, filtrarPasswords
this.enviarForm = function() {
if (!this.xmlHttpReq) return false;
if (arguments[1]) {
this.urlReceptor = arguments[1];
if (arguments[2]) {
this.metodo = arguments[2];
if (arguments[3]) {
this.sync = arguments[3];
if (arguments[4]) {
if (arguments[5]) {
this.cargarForm(arguments[4], arguments[5]);
}
else
{
this.cargarForm(arguments[4]);
}
}
}
}
}
var metodobak = this.metodo;
this.metodo = metodo.get;
this.xmlHttpReq.open(this.metodo, this.urlReceptor, this.sync);
this.xmlHttpReq.setRequestHeader('User-Agent','xmlHttpReq/1.0');
this.xmlHttpReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
this.xmlHttpReq.setRequestHeader('Cache-Control', 'must-revalidate');
this.xmlHttpReq.setRequestHeader('Cache-Control', 'no-cache');
this.xmlHttpReq.onreadystatechange = this.onStateChange;
this.xmlHttpReq.send(this.form);
this.metodo = metodobak;
}

// método enviar: envía un mensaje
// recibe el mensaje y opcionalmente, en orden: urlReceptor, metodo, sync
this.enviar = function (mensajeXML) {
if (!this.xmlHttpReq) return false;
if (arguments[1]) {
this.urlReceptor = arguments[1];
if (arguments[2]) {
this.metodo = arguments[2];
if (arguments[3]) {
this.sync = arguments[3];
}
}
}
this.xmlHttpReq.open(this.metodo, this.urlReceptor, this.sync);
this.xmlHttpReq.onreadystatechange = this.onStateChange;
this.xmlHttpReq.setRequestHeader('User-Agent','xmlHttpReq/1.0');
this.xmlHttpReq.setRequestHeader('Content-Type', 'text/html;charset=windows-1252');
this.xmlHttpReq.setRequestHeader('Cache-Control', 'must-revalidate');
this.xmlHttpReq.setRequestHeader('Cache-Control', 'no-cache');
this.xmlHttpReq.send(xmlMessage);
}

this.onStateChange = function() { fOnStateChange(this.xmlHttpReq); }
}

function instanciarXMLHTTPReq() {
XMLHttp = false;
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
else if (window.ActiveXObject) {
var versiones = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "Msxml2.XMLHTTP.3.0", "Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];
for (var i=0; i<versiones.length; i++) {
try {
XMLHttp = new ActiveXObject(versiones[i]);
if (XMLHttp) {
return XMLHttp;
break;
}
}
catch (e) {};
}
}
}

function fOnStateChange(xmlHttpReq) {
window.alert('1');
if (!xmlHttpReq) return false;
window.alert('2');
if (xmlHttpReq.readyState==4) { // 4 = "loaded"
window.alert('3');
if (xmlHttpReq.status==200) { // 200 = OK
window.alert('4');
switch (this.tipo) {
case tipo.xml:
window.alert('5');
this.funProcResp(xmlHttpReq.responseXML);
break;
case tipo.texto:
window.alert('6');
this.funProcResp(xmlHttpReq.responseText);
break;
case tipo.json:
window.alert('7');
this.funProcResp(xmlHttpReq.responseText.evalJSON( ));
break;
}
}
}
}