Ir para conteúdo

POWERED BY:

Arquivado

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

ThiagoInfo

addEventListener + setTimeout - atualizar vários dados

Recommended Posts

Olá pessoal,

 

Queria uma força em um problema que estou tendo.. já procurei em tudo quanto foi lugar, mas não achei a solução, já li em vários fóruns gringos, mas nada também.

 

Eu tenho o seguinte script:

var xmlhttp = getXmlHttpRequest();


function getXmlHttpRequest()
{
   if (window.XMLHttpRequest)
   {
	  return new XMLHttpRequest();
   }
   else if (window.ActiveXObject)
   {
	  try
	  {
		 return new ActiveXObject("Msxml2.XMLHTTP");
	  }
	  catch (e)
	  {
		 try
		 {
			return new ActiveXObject("Microsoft.XMLHTTP");
		 }
		 catch (e){}
	  }
   }
}

function ajax(arquivo,divID)
{
	  xmlhttp.open("POST", arquivo,true);
	  xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	  xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
	  xmlhttp.setRequestHeader("Pragma", "no-cache");
	  xmlhttp.onreadystatechange = function()
	  {
		 if (xmlhttp.readyState==1)
		 {
			document.getElementById(divID).innerHTML =  "<img src='./img/atualizando.gif' />";
		 }
		 if (xmlhttp.readyState==4)
		 {
			if (xmlhttp.status == 200) {
			   var resultado = xmlhttp.responseText; // Coloca o retornado pelo Ajax nessa variável
			   document.getElementById(divID).innerHTML = resultado; 
			}
		 }
	  }
	  xmlhttp.send(null);
setTimeout("ajax('"+arquivo+"','"+divID+"')", 30000);
}

function bodyOnReady(func){
 //call the function 'func' when DOM loaded
 //Version 3.0 - 15/10/2008 - based on Jquery bindReady
 //by Micox - www.elmicox.com - elmicox.blogspot.com - webly.com.br
 //http://www.elmicox.com/2007/evento-body-onready-sem-o-uso-de-libs/

	//flag global para indicar que já rodou e function que roda realmente
	done = false
	init = function(){ if(!done) { done=true; func() } }
	var d=document; //apelido para o document
	//pra quem tem o DOMContent (FF)
	if(document.addEventListener){ d.addEventListener("DOMContentLoaded", init, false );}
	
	if( /msie/i.test( navigator.userAgent ) ){ //IE
		(function () {
			try { // throws errors until after ondocumentready				
				d.documentElement.doScroll("left");
			} catch (e) {
				setTimeout(arguments.callee, 10); return;
			}
			// no errors, fire
			init();
		})();
	}
	if ( window.opera ){
		d.addEventListener( "DOMContentLoaded", function () {
			if (done) return;
			//no opera, os estilos só são habilitados no fim do DOMready
			for (var i = 0; i < d.styleSheets.length; i++){
				if (d.styleSheets[i].disabled)
					setTimeout( arguments.callee, 10 ); return;
			}
			// fire
			init();
		}, false);
	}
	if (/webkit/i.test( navigator.userAgent )){ //safari's
		if(done) return;
		//testando o readyState igual a loaded ou complete
		if ( /loaded|complete/i.test(d.readyState)===false ) {
			setTimeout( arguments.callee, 10 );	return;
		}
		init();
	}
	//se nada funfou eu mando a velha window.onload lenta mesmo
	if(!done) window.onload = init
}
bodyOnReady(function(){
	ajax("./cont/data.php","data-atual");
	ajax("./cont/visitas.php","visitas");
});

Ele está funcionando Ok...

 

Só tem um problema, quando eu adiciono a segunda "função", os meus dados referente as visitas atualiza sem problemas, mas hora até atualiza, mas hora que ela vai dar o refresh no caso a cada 30 segundos ou hora que carrego a página, ele fica carregando um tempo muito grande até aparecer a hora e aí hora que precisa atualizar novamente ele demora também.

 

Se eu tirar uma das funções por exemplo:

ajax("./cont/visitas.php","visitas");

A funciona normalmente, mas se eu adicionar mais divs e dados pra carregar acontece isto, alguém poderia me ajudar?

Eu já testei onload, já coloquei duas funções mas dá n mesma.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Bom conseguir arrumar uma função que funciona, caso alguém precise, eu que tinha muita gente querendo, vai então a solução:

var xmlhttp = false;

if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
{
  try {
	xmlhttp = new XMLHttpRequest ();
  }
  catch (e) {
  xmlhttp = false}
}


function myXMLHttpRequest (){
  var xmlhttplocal;
  try {
	  xmlhttplocal = new ActiveXObject ("Msxml2.XMLHTTP")}
  catch (e) {
	try {
	xmlhttplocal = new ActiveXObject ("Microsoft.XMLHTTP")}
	catch (E) {
	  xmlhttplocal = false;
	}
  }

  if (!xmlhttplocal && typeof XMLHttpRequest != 'undefined') {
	try {
	  var xmlhttplocal = new XMLHttpRequest ();
	}
	catch (e) {
	  var xmlhttplocal = false;
	}
  }
  return (xmlhttplocal);
}

var mnmxmlhttp = Array ();
var mnmString = Array ();
var mnmPrevColor = Array ();
var responsestring = Array ();
var myxmlhttp = Array ();
var responseString = new String;

var i=0;
var ii = 0;

function ajax_update(myUrl, myDiv, rate){

	target2 = document.getElementById ('content');

	ii = i++;

	var content = "i=" + ii;

	mnmxmlhttp = new myXMLHttpRequest ();
	if (mnmxmlhttp) {
			mnmxmlhttp.open ("POST", myUrl, true);
			mnmxmlhttp.setRequestHeader ('Content-Type',
					   'application/x-www-form-urlencoded');

			mnmxmlhttp.send (content);
			errormatch = new RegExp ("^ERROR:");

			target2 = document.getElementById (myDiv);

			mnmxmlhttp.onreadystatechange = function () {
				if (mnmxmlhttp.readyState == 4) {
					mnmString = mnmxmlhttp.responseText;

					if (mnmString.match (errormatch)) {
						mnmString = mnmString.substring (6, mnmString.length);

						target = document.getElementById (myDiv);
						target2.innerHTML = mnmString;

					} else {
						target = document.getElementById (myDiv);
						target2.innerHTML = mnmString;
					}
				}
			}
		}

	setTimeout('ajax_update(\'' + myUrl + '\',\'' + myDiv + '\',\'' + rate + '\');', rate);
}


function bodyOnReady(func){
 //call the function 'func' when DOM loaded
 //Version 3.0 - 15/10/2008 - based on Jquery bindReady
 //by Micox - www.elmicox.com - elmicox.blogspot.com - webly.com.br
 //http://www.elmicox.com/2007/evento-body-onready-sem-o-uso-de-libs/

	//flag global para indicar que já rodou e function que roda realmente
	done = false
	init = function(){ if(!done) { done=true; func() } }
	var d=document; //apelido para o document
	//pra quem tem o DOMContent (FF)
	if(document.addEventListener){ d.addEventListener("DOMContentLoaded", init, false );}
	
	if( /msie/i.test( navigator.userAgent ) ){ //IE
		(function () {
			try { // throws errors until after ondocumentready				
				d.documentElement.doScroll("left");
			} catch (e) {
				setTimeout(arguments.callee, 10); return;
			}
			// no errors, fire
			init();
		})();
	}
	if ( window.opera ){
		d.addEventListener( "DOMContentLoaded", function () {
			if (done) return;
			//no opera, os estilos só são habilitados no fim do DOMready
			for (var i = 0; i < d.styleSheets.length; i++){
				if (d.styleSheets[i].disabled)
					setTimeout( arguments.callee, 10 ); return;
			}
			// fire
			init();
		}, false);
	}
	if (/webkit/i.test( navigator.userAgent )){ //safari's
		if(done) return;
		//testando o readyState igual a loaded ou complete
		if ( /loaded|complete/i.test(d.readyState)===false ) {
			setTimeout( arguments.callee, 10 );	return;
		}
		init();
	}
	//se nada funfou eu mando a velha window.onload lenta mesmo
	if(!done) window.onload = init
}

para usar:

 

bodyOnReady(function(){
	ajax_update('arquivo','elementoID', tempo refresh);
});

pode adicionar quantos quiser(EX):

bodyOnReady(function(){
	ajax_update('./cont/data.php','hora-atual',10000);
	ajax_update('./cont/visitas.php','visitas', 30000);
});

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.