Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

ThiagoInfo

Multi Carregamento a cada tempo

Recommended Posts

Olá pessoal,

 

Bom acho que devemos sempre compartilhar nossas soluções, descobertas, etc.

 

Pois bem eu passei um bom tempo para conseguir achar uma solução para fazer multi carregamento em X tempo determinado.

 

Eu consegui uma, mas que quando eu usava mais de 3 vezes, ele já não funcionava, só funciona duas.

 

Continuei a procurar até que achei, pelo menos acho e até agora a solução perfeita.

 

Gostaria de dizer que ainda sou iniciante em ajax e se alguém quiser ajudar ou achar algo que esteja errado, favor postar.

 

Vamos ao script:

var xhr = new Array(); // ARRAY OF XML-HTTP REQUESTS
var xi = new Array(0); // ARRAY OF XML-HTTP REQUEST INDEXES
xi[0] = 1; // FIRST INDEX SET TO 1 MAKING IT AVAILABLE

function xhrRequest(type) {
if (!type) {
type = 'html';
}


// xhrsend IS THE xi POSITION THAT GETS PASSED BACK
// INITIALIZED TO THE LENGTH OF THE ARRAY(LAST POSITION + 1)
// IN CASE A FREE RESOURCE ISN'T FOUND IN THE LOOP
var xhrsend = xi.length;

// GO THROUGH AVAILABLE xi VALUES
for (var i=0; i<xi.length; i++) {

// IF IT'S 1 (AVAILABLE), ALLOCATE IT FOR USE AND BREAK
if (xi[i] == 1) {
xi[i] = 0;
xhrsend = i;
break;
}
}

// SET TO 0 SINCE IT'S NOW ALLOCATED FOR USE
xi[xhrsend] = 0;

// SET UP THE REQUEST
if (window.ActiveXObject) {
try {
xhr[xhrsend] = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr[xhrsend] = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
} else if (window.XMLHttpRequest) {
xhr[xhrsend] = new XMLHttpRequest();
if (xhr[xhrsend].overrideMimeType) {
xhr[xhrsend].overrideMimeType('text/' + type);
}
}
return (xhrsend);
}

function atualiza_dados(arquivo, elementoID, tempoR) {
	
var xhri = xhrRequest('html');
xhr[xhri].open('GET', arquivo, true);
xhr[xhri].setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
xhr[xhri].setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
xhr[xhri].setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
xhr[xhri].setRequestHeader("Pragma", "no-cache");
xhr[xhri].onreadystatechange = function() {
	
if (xhr[xhri].readyState == 1) {
	document.getElementById(elementoID).innerHTML = "<img src='./img/atualizando.gif' />";
	}
if (xhr[xhri].readyState == 4 && xhr[xhri].status == 200) {
	document.getElementById(elementoID).innerHTML = xhr[xhri].responseText;
	xi[xhri] = 1;
	xhr[xhri] = null;
	}
};
xhr[xhri].send(null);
setTimeout("atualiza_dados('" + arquivo + "','" + elementoID + "','" + tempoR + "')", tempoR);
}

function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}

Está ai acima a adaptação.

 

Para usar:

addEvent(window, 'load', function(){
	atualiza_dados('exemplo.php?crt=exemplo1','exemplo1', 30000);
	atualiza_dados('exemplo.php?crt=exemplo2','exemplo2', 30000);
});
<div id="exemplo1"><!-- vai recarregar a cada tempo definido--></div>
<div id="exemplo2"><!-- vai recarregar a cada tempo definido--></div>

exemplo.php

<?php
if ($_GET['crt'] == 'exemplo1'){
echo "este é exemplo1, da primeira div, vai atualizar a cada 30 segundos";
}
if ($_GET['crt'] == 'exemplo2'){
echo "este é exemplo2, da segunda div, vai atualizar a cada 30 segundos";
}
?>

Você pode chamar vários arquivos, ou usar apenas um e usar querystring como no exemplo ou fazer um mix.

 

Esse script é útil por exemplo pra quem usa navegação via ajax e precisa atualiza hora, visistas, banners de publicidade imagens com rand, etc.

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.