Comunidad de diseño web y desarrollo en internet online

Recibir contenido javascript en una peticion AJAX

Citar            
MensajeEscrito el 23 Dic 2008 08:00 pm
Buenas tardes:

He buscado y rebuscado y no he localizado una solución para este problema. Tengo una página que hace una petición asíncrona de otra, para cargarla en un contenedor. Dentro del cuerpo de la página que cargo, hay un script que debería ejecutar, pero este no carga, solamente el contenido HTML puro. He creído entender que si cargo la página como si fuese XML e inserto el contenido haciendo referencia al nodo que debería contener el script. ¿Alguien tiene idea?

Muchas gracias. Un saludo

Por pcampa

0 de clabLevel



 

firefox
Citar            
MensajeEscrito el 15 Ene 2009 06:19 pm
Espero sirva de algo para continuar con la idea.,

PETICION CAROLINA escribió:

<SCRIPT src="/js/peticion_ajax.js" type="text/javascript"></SCRIPT>

<script type="text/javascript">

var a1 = '<%= a1 %>'
var nombre ='<%= nombre %>'
var precio =' <%= precio.toFixed(3) %>'
var campo2 ='<%= campo2 %>'
var campo1 ='<%= campo1 %>'
var a1x ='<%= a1x %>'
var codbarra ='<%= codbarra %>'
var usuario ='<%= usuario %>'
var grilla ='<%= grilla %>'


function registrarForm(frm) {
form_CarroCompra= new Formulario(frm);
$('cantidad').focus();
};



function guardarDatos () {

if (!form_CarroCompra.procesarForm()) {
alert("no procesa")
}
p=[]
p['a1x'] = a1x
p['a1'] = a1
p['cantidad'] = $('cantidad').value
p['peso'] = $('peso').value
p['codbarra'] = $('id').value
peticion('dondesehacelapeticion.asp','P','S',p,manejadorPeticion,false,true)

};

function manejadorPeticion(respuesta,p) {

if (grilla=="Catalogo") {
var nodoItem = window.parent.GrillaPeticion2.xmlDatos.selectSingleNode("//item[@a1x="+ p['a1x'] + "]")
} else {
var nodoItem = window.parent.GrillaPeticion.xmlDatos.selectSingleNode("//item[@a1x="+ p['a1x'] + "]")
window.parent['total'].innerHTML = respuesta
}

if (nodoItem) {
nodoItem.setAttribute("cantidad") = p['cantidad']
nodoItem.setAttribute("peso") = p['peso']
if (grilla=="Catalogo") {
window.parent.GrillaPeticion2.updateXmlSource();
window.parent.GrillaPeticion2.agregarDesdeXml( 0 , 'q');
}
else {
window.parent.GrillaPeticion.updateXmlSource();
window.parent.GrillaPeticion.agregarDesdeXml( 0 , 'q');
}
alert("Datos grabados correctamente.")
window.parent['abmOferta'].cerrar();
}

};




</script>

peticion_ajax.js escribió:



//INSTANCIA EL OBJETO y SETEA LOS VALORES NECESARIOS

//peticion(pagina que procesa,'tipo de envio g/p','sincornismo a/s',array con parametros,función manejador)
//implementa: <a href="#" onClick="peticion('nomcom_tirar.asp','P','A',parametros,respuesta);return false;">buscar</a>

//El array con parámetros debe estar declarado con ese nombre en la página de origen de esta forma:
//var parametros = new Array()
//parametros['id'] = '7'

//La función que hará de manejador debe estar declarada en la página de origen y puede tener cualquier nombre, ya que la misma función se pasará como parámetro.

//La clase ya instancia el objeto xmlhttprequest


//dibujo el cargador
dibujarCargador()
dibujarDivModal()

var objPeticion
function peticion(url,envio,tipo,parametros,manejador,depurar,activarCargador){
objPeticion = null;
objPeticion = new peticion_ajax(url,envio,tipo,parametros,manejador,depurar,activarCargador);
if ( depurar ) objPeticion.depurarOn();
objPeticion.validarDatos();
if ( typeof activarCargador == 'boolean' ) objPeticion.setActivarCargador(activarCargador);
objPeticion.ejecutar();
};

//Clase -------------------------------------------------------------------------------
function peticion_ajax(url,envio,tipo,parametros,manejador,depurar){
//PROPIEDADES
this.xmlhttp = _instancio_xmlhttp();
this.envio = envio; //GET O POST
this.tipo = tipo; // SINC O ASINC
this.metodo = true;// TRUE SI ASINC - FALSE SI SINC
this.url = url;
this.parametros = devolver_parametros(parametros);
this.arrayParametros = parametros;
this.manejador = manejador;
this.msg = "";
this.retorno = true;
this.arguments = arguments.length;
this.estados = new Array("UNINITIALIZED - The object has been created, but not initialized (open method has not been called).\n","LOADING - The object has been created, but the send method has not been called.\n","LOADED - The send method has been called and the status and headers are available, but the response is not yet available.\n","INTERACTIVE - Some data has been received. You can call responseBody and responseText to get the current partial results.\n","COMPLETED - All the data has been received, and the complete data is available in responseBody and responseText.\n");
this.depurar_bandera = false;
this.datos_enviar = null;
this.activarCargador = true;

//METODOS
this.depurarOn = _depurarOn;
this.depurarOff = _depurarOff;
this.validarDatos = _validarDatos;
this.ejecutar = _realizarPeticion;
this.mostrarDatosInternos = _mostrarDatosInternos;
this.manejarAsync = _manejarAsync;
this.armarUrl = _armarUrl;
this.setActivarCargador = _setActivarCargador;

this.armarUrl();

};

//--------------------------------------------------------
//REALIZA LA PETICION AL SERVIDOR
function _realizarPeticion() {
var peticion_respuesta = "";
toogleCargador(true,this.activarCargador);
//enabledModalDiv();
try {
if ( this.metodo ) {
//SI EL METODO ES ASINCRONICO
this.xmlhttp.open(this.envio,this.url,true);
objXmlhttp = this.xmlhttp;
this.xmlhttp.setRequestHeader('Accept','message/x-formresult');
this.xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
this.xmlhttp.send(this.datos_enviar);
this.xmlhttp.onreadystatechange = this.manejarAsync;
}else{
//SI EL METODO ES SINCRONICO
this.xmlhttp.open(this.envio,this.url,false);
this.xmlhttp.setRequestHeader('Accept','message/x-formresult');
this.xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//this.xmlhttp.setRequestHeader("Content-Type: text/plain; charset=ISO-8859-1")
this.xmlhttp.send(this.datos_enviar);
if (this.xmlhttp.status !== 200 && this.xmlhttp.status !== 204 ) {
if(this.xmlhttp.status == 12007 || this.xmlhttp.status == 12029){
this.msg += "La conexión se ha interrumpido.\nPor favor inicie sesión nuevamente.";
peticion_respuesta = this.xmlhttp.responseText;
}else{
this.msg += "Problema con la petición: " + this.xmlhttp.statusText;
peticion_respuesta = this.xmlhttp.responseText;

if( window.top.principal ){
if( window.top.principal.Consola ){
if(window.top.principal.Consola.errores){
window.top.principal.Consola.errores.push(peticion_respuesta)
}
}
}

if(this.depurar_bandera){
this.mostrarDatosInternos();
abrirPopup(peticion_respuesta);

}
}
this.retorno = false;
} else {
peticion_respuesta = this.xmlhttp.responseText;
this.manejador(peticion_respuesta,this.arrayParametros);
this.retorno = true;
if(this.depurar_bandera) this.mostrarDatosInternos();
}
//OCULTA EL CARGADOR
toogleCargador(false,this.activarCargador);
//disabledModalDiv()
}
} catch(e) {
//CAPTURA EL ERROR SI EXISTE EN EL TRY
this.msg += e;
this.retorno = false;
//OCULTA EL CARGADOR
toogleCargador(false,this.activarCargador);
//disabledModalDiv()
}

if ( !this.retorno ) {
//MUESTRA EL ERROR
alert(this.msg);
}


//if(this.depurar_bandera) alert(this.msg)
//toogleCargador(false,this.activarCargador)
return this.retorno;
};

/*function _obtenerErroresAsp () {
this.xmlhttp.open('GET','erroresAsp.asp',false);
this.xmlhttp.setRequestHeader('Accept','message/x-formresult')
this.xmlhttp.send()
if ( this.xmlhttp.status != 200 ) {
this.msg += "\nErrores Asp: No se puede acceder a la página de errores ( " + this.xmlhttp.statusText + " )"
}else{
this.msg += "\nErrores Asp: " + this.xmlhttp.responseText
}
}*/

function _manejarAsync(){
if ( objXmlhttp.readyState == 4 ){
if ( objXmlhttp.status !== 200 && objXmlhttp.status !== 204 ) {
//OCULTA EL CARGADOR
toogleCargador(false,objPeticion.activarCargador);
//disabledModalDiv()
if(objXmlhttp.status == 12007 || objXmlhttp.status == 12029){
objPeticion.msg += "Se ha perdido la conexión. Por favor inicie sesión nuevamente.";
peticion_respuesta = objXmlhttp.responseText;
}else{
objPeticion.msg += "Problema con la respuesta http: " + objXmlhttp.statusText;
peticion_respuesta = objXmlhttp.responseText;

if( window.top.principal ){
if( window.top.principal.Consola ){
if(window.top.principal.Consola.errores){
window.top.principal.Consola.errores.push(peticion_respuesta)
}
}
}

if(objPeticion.depurar_bandera) {
//objPeticion.obtenerErroresAsp()
objPeticion.mostrarDatosInternos();
abrirPopup(peticion_respuesta);
}
}
objPeticion.retorno = false;
alert(objPeticion.msg);
} else {
//OCULTA EL CARGADOR
toogleCargador(false,objPeticion.activarCargador);
//disabledModalDiv()
peticion_respuesta = objXmlhttp.responseText;
objPeticion.manejador(peticion_respuesta,objPeticion.arrayParametros);
objPeticion.retorno = true;
if(objPeticion.depurar_bandera) objPeticion.mostrarDatosInternos();
}
} else {
//objPeticion.msg += objXmlhttp.readyState + " - " + objPeticion.estados[objXmlhttp.readyState-1]
//objPeticion.msg += objXmlhttp.readyState + ", "
}
};

function _mostrarDatosInternos(){
var out = "Salida para la depuración: ";
out += "\n" + "msg: " + this.msg;
out += "\n" + "statusText: " + this.xmlhttp.statusText;
out += "\n" + "readyState: " + this.xmlhttp.readyState;
//out += "\n" + "readyState descripción: " + this.estados[this.xmlhttp.readyState-1]
out += "\n" + "url: " + this.url;
out += "\n" + "retorno: " + this.retorno;
out += "\n" + "aSync: " + this.metodo;
out += "\n" + "método envío: " + this.envio;
out += "\n" + "manejador: " + typeof(this.manejador) + " " + this.manejador.name;
out += "\n" + "parametros recibidos: " + this.parametros;
//out += "\n" + "getAllResponseHeaders: " + this.xmlhttp.getAllResponseHeaders()

alert ( out );
};

function _depurarOff() {
this.depurar_bandera = false;
};

function _depurarOn() {
this.depurar_bandera = true;
};

//VERIFICA LOS DATOS RECIBIDOS POR EL OBJETO
function _validarDatos(){
//VERIFICA LA CANTIDAD DE ARGUMENTOS
if (this.arguments.length < 5) {
this.msg += "La cantidad de argumentos que recibió la función es incorrecta";
this.retorno = false;
alert(this.msg);
for(i in this.arguments) {
this.msg += "\n" + "Argumento: " + i + ". Valor: " + this.arguments[i];
}
return false;
}
//VERIFICA EL TIPO DE LLAMADA
if ( this.tipo == "a" || this.tipo == "A" ) {
this.metodo = true;
} else if ( this.tipo == "s" || this.tipo == "S" ) {
this.metodo = false;
} else {
this.msg += "El tipo de llamada no está correctamente definido (a/A: asincrónico - s/S: sincrónico)";
this.retorno = false;
alert(this.msg);
return false;
}

//VERIFICA LA FUNCION QUE MANEJARA EL RESULTADO
if ( typeof(this.manejador) != "function" && this.manejador != '' ) {
msg += "El manejador de resultado no está definido.";
this.retorno = false;
alert(this.msg);
return false;
}else if (this.manejador=='') {
this.manejador = 'sinManejador';
}
//VERIFICA LA URL
if ( this.url.length == 0 ) {
this.msg += "Parámetro url vacío."
this.retorno = false;
alert(this.msg);
return false;
}

//VERIFICA EL TIPO DE ENVIO
if ( this.envio == "g" || this.envio == "G" ) {
this.envio = "GET";
}else if ( this.envio == "p" || this.envio == "P") {
this.envio = "POST";
}else {
this.msg += "El tipo de envío no está correctamente definido (g/G: GET - p/P: POST)";
this.retorno = false;
alert(this.msg);
return false;
}


};

function _instancio_xmlhttp () {
var xmlhttp = null;

/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
} catch (E) {
xmlhttp=false;
}
}
@else
xmlhttp=false;
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false;
}
}
return xmlhttp;
};


function devolver_parametros(parametros) {
if (typeof(parametros)=='object') {
//return $H(parametros).toQueryString()

if( typeof gidmodulo != 'undefined' ){
var str = '&modulo='+gidmodulo;
}else if( typeof window.parent.gidmodulo != 'undefined' ){
var str = '&modulo='+window.parent.gidmodulo;
}else if( typeof window.parent.parent.gidmodulo != 'undefined' ){
var str = '&modulo='+window.parent.parent.gidmodulo;
}else if( typeof window.parent.parent.parent.gidmodulo != 'undefined' ){
var str = '&modulo='+window.parent.parent.parent.gidmodulo;
}else{
var str = '';
}

for (i in parametros) {
if (typeof(parametros[i]) != 'function')
str += "&"+i+"="+parametros[i];
}
if (str != '') {
return str.substr(1,str.length);
}else{
return '';
}
}else{
return '';
}
};

function abrirPopup (datos) {
var ventana = window.open("", "popup", "width=500,height=350,status=no,resizable=yes,toolbar=no,menubar=no,titlebar=no, scrollbars=yes");
ventana.document.write(datos);
ventana.focus();
};

function dibujarDivModal(){
document.write('<div id="divmodal" name="divmodal" style="position:absolute;z-index:100000;display:none;" class="modal" unselectable="on" galleryimg="no"></div><div id="divreloj" align="center" style="position:absolute;z-index:100001;display:none;"><img src="/imagenes/relojArena.gif" border="0"/></div>')
}

function enabledModalDiv()
{
if( $("divmodal") ){

if( $("divmodal").style.display == "" ) return;

function aux(){return false; };
$("divmodal").onselectstart = aux;
$("divmodal").ondragstart = aux;
$("divmodal").onmouseover = aux;
$("divmodal").onmousemove = aux;
$("divmodal").onmouseup = aux;
$("divmodal").oncontextmenu = aux;
$("divmodal").style.left = 0 + document.body.scrollLeft;
$("divmodal").style.top = 0 + document.body.scrollTop;
$("divmodal").style.width = window.document.body.clientWidth;
$("divmodal").style.height = window.document.body.clientHeight;

$("divreloj").style.left = 0 + (document.body.clientWidth / 2);
$("divreloj").style.top = 0 + (document.body.clientHeight / 2);

$("divmodal").style.display = "";
$("divreloj").style.display = "";
}
};

function disabledModalDiv()
{
$("divmodal").style.display = "none";
$("divreloj").style.display = "none";
};
function dibujarCargador() {
document.write('<div id="cargadorListado" style="width:154px;height:68px;position:absolute; left:38%; top:40%; z-index:99;visibility:hidden;"><table width="154" height="68" border="0" align="center" cellpadding="0" cellspacing="0"><tr><td align="center" background="/imagenes/fondo_carga.gif"><table width="85%" height="64" border="0" cellpadding="0" cellspacing="0"><tr><td height="20" align="left" style="font-family: Tahoma; font-size: 7pt; font-weight: bold; color: #333333;">Cargando...</td></tr><tr><td height="42" align="center"><img src="/imagenes/indicator.gif" width="16" height="16" /></td></tr></table></td></tr></table></div>');
};

function _setActivarCargador(bool) {
this.activarCargador = bool
};

function toogleCargador(accion, activarCargador){

if ( !activarCargador ) return;
//var mostrar = "";
if ( accion == true ) {
enabledModalDiv();
//mostrar = "visible";
}else if ( accion == false ) {
disabledModalDiv();
//mostrar = "hidden";
}else if ( document.getElementById("cargadorListado").style.visibility == "hidden" ) {
//mostrar = "visible";
}else{
//mostrar = "hidden";
}

//document.getElementById("cargadorListado").style.top = (document.body.clientHeight / 2) - 34 + document.body.scrollTop
//document.getElementById("cargadorListado").style.visibility = mostrar;
};

function _armarUrl() {
if(this.envio == "G") {
if (this.parametros != '') this.url += "?" + this.parametros;
}else{
this.datos_enviar = this.parametros;
}
};

function sinManejador() {
return false;
};

Por carolinaspanesi

30 de clabLevel



 

firefox
Citar            
MensajeEscrito el 16 Ene 2010 03:26 pm
Carolina, lei tu post, pero el ejemplo que citas no es la solucion al inconveniente planteado.
Para realizar una peticion sincronica o asincronica, insertar contenido HTML y luego evaluar los scripts que vienen dentro de la misma peticion existe una libreria en javascript llamada prototype.js y es open source, o sea no tenemos que preocuparnos de nada siempre y cuando no removamos las "leyendas de su autor".
La libreria pueden descargarla de http://www.prototypejs.org/

Proximamente pondré un ejemplo

Por marcossalto

0 de clabLevel



 

msie8

 

Cristalab BabyBlue v4 + V4 © 2011 Cristalab
Powered by ClabEngines v4, HTML5, love and ponies.