Ir para conteúdo

POWERED BY:

Arquivado

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

cerberowski

Acentuação com ASP e Ajax (XMLHttpRequest)

Recommended Posts

Olá,

Estou perdendo os cabelos nesse código "maledeto".

Peguei esse código no site www.dynamicdrive.com, mas ele não aceita acentos (aparecem caracteres estranhos tanto no FF quanto no IE)

 

Por favor, alguém me ajude.

Já olhei diversos tópicos sobre o assunto, fiz diversas tentativas mas não consegui, por isso estou postando.

 

Apenas para tentar explicar esse script:

A primeira página (ASP) lê um arquivo TXT (utilizando XMLHttpRequest) que contém diversas mensagens (dentro de DIVs) onde elas serão mostradas a cada 3.5 segundos cada uma. Ou seja, mostra a primeira, aguarda 3.5 segundos, mostra a segunda... E assim por diante. O problema é que essas mensagens não podem conter acentos... E isso é que está me matando.

 

 

O mais próximo que cheguei foi colocar no início do arquivo TXT a linha

<?xml version="1.0" encoding="iso-8859-1"?>
E com isso funcionou no FF, mas no IE continua não funcionando

 

 

 

Abaixo, estão os códigos para que possam me ajudar:

Obs.: Já peço desculpas caso a mensagem tenha ficado longa, mas estou desesperado...

 

Arquivo JS com o script que abre o arquivo TXT

// -------------------------------------------------------------------
// Ajax XML Ticker (txt file source)
// Author: Dynamic Drive (http://www.dynamicdrive.com)
// -------------------------------------------------------------------

////////////No need to edit beyond here//////////////

function createAjaxObj(){
	var httprequest=false
	if (window.XMLHttpRequest){ // if Mozilla, Safari etc
		httprequest_AjaxObj=new XMLHttpRequest()
		if (httprequest_AjaxObj.overrideMimeType){
			httprequest_AjaxObj.overrideMimeType('text/xml') // ORIG
		}
	} else if (window.ActiveXObject){ // if IE
		try {
			httprequest_AjaxObj=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e){
			try{
				httprequest_AjaxObj=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	}
	return httprequest_AjaxObj
}

// -------------------------------------------------------------------
// Main Ajax Ticker Object function
// ajax_ticker(xmlfile, divId, divClass, delay, optionalfadeornot)
// -------------------------------------------------------------------

function ajax_ticker(xmlfile, divId, divClass, delay, fadeornot){
	this.xmlfile=xmlfile //Variable pointing to the local ticker xml file (txt)
	this.tickerid=divId //ID of ticker div to display information
	this.delay=delay //Delay between msg change, in miliseconds.
	this.mouseoverBol=0 //Boolean to indicate whether mouse is currently over ticker (and pause it if it is)
	this.pointer=0
	this.opacitystring=(typeof fadeornot!="undefined")? "width: 100%; filter:progid:DXImageTransform.Microsoft.alpha(opacity=100); -moz-opacity: 1" : ""
	if (this.opacitystring!="") this.delay+=500 //add 1/2 sec to account for fade effect, if enabled
	this.opacitysetting=0.2 //Opacity value when reset. Internal use.
	this.messages=[] //Arrays to hold each message of ticker
	httprequest_AjaxObj=createAjaxObj()
	document.write('<div id="'+divId+'" class="'+divClass+'"><div style="'+this.opacitystring+'">Inicializando...</div></div>')
	this.getXMLfile()
}

// -------------------------------------------------------------------
// getXMLfile()- Use Ajax to fetch xml file (txt)
// -------------------------------------------------------------------

ajax_ticker.prototype.getXMLfile=function(){
	if (httprequest_AjaxObj){
		var instanceOfTicker=this
		var url=this.xmlfile+"?bustcache="+new Date().getTime()
		httprequest_AjaxObj.onreadystatechange=function(){instanceOfTicker.initialize()}
		httprequest_AjaxObj.open('GET', url, true)
		httprequest_AjaxObj.send(null)
	}
}

// -------------------------------------------------------------------
// initialize()- Initialize ticker method.
// -Gets contents of xml file and parse it using JavaScript DOM methods
// -------------------------------------------------------------------
ajax_ticker.prototype.initialize=function(){
	if (httprequest_AjaxObj.readyState == 4){ //if request of file completed
		if (httprequest_AjaxObj.status==200 || window.location.href.indexOf("http")==-1){ //if request was successful
			this.contentdiv=document.getElementById(this.tickerid).firstChild //div of inner content that holds the messages
			var xmldata = httprequest_AjaxObj.responseText
		   
			this.contentdiv.style.display="none"
			this.contentdiv.innerHTML=xmldata;
		   
		   
			if (this.contentdiv.getElementsByTagName("div").length==0){ //if no messages were found
				this.contentdiv.innerHTML="<b>Erro</b> ao obter mensagens!"
				return
			}
			var instanceOfTicker=this
			document.getElementById(this.tickerid).onmouseover=function(){instanceOfTicker.mouseoverBol=1}
			document.getElementById(this.tickerid).onmouseout=function(){instanceOfTicker.mouseoverBol=0}
			if (window.attachEvent){ //Clean up loose references in IE
				window.attachEvent("onunload", function(){
						instanceOfTicker.contentdiv=instanceOfTicker.httprequest_AjaxObj=null
					}
				)
			}
			//Cycle through XML object and store each message inside array
			for (var i=0; i<this.contentdiv.getElementsByTagName("div").length; i++){
				if (this.contentdiv.getElementsByTagName("div")[i].className=="message"){
					this.messages[this.messages.length] = this.contentdiv.getElementsByTagName("div")[i].innerHTML;
				}
			}
			this.contentdiv.innerHTML=""
			this.contentdiv.style.display="block"
			this.rotatemsg()
		}
	}
}

// -------------------------------------------------------------------
// rotatemsg()- Rotate through ticker messages and displays them
// -------------------------------------------------------------------

ajax_ticker.prototype.rotatemsg=function(){
	var instanceOfTicker=this
	if (this.mouseoverBol==1) //if mouse is currently over ticker, do nothing (pause it)
		setTimeout(function(){instanceOfTicker.rotatemsg()}, 100)
	else{ //else, construct item, show and rotate it!
		this.fadetransition("reset") //FADE EFFECT- RESET OPACITY
		this.contentdiv.innerHTML=this.messages[this.pointer]
		this.fadetimer1=setInterval(function(){instanceOfTicker.fadetransition('up', 'fadetimer1')}, 100) //FADE EFFECT- PLAY IT
		this.pointer=(this.pointer<this.messages.length-1)? this.pointer+1 : 0
		setTimeout(function(){instanceOfTicker.rotatemsg()}, this.delay) //update container periodically
	}
}

// -------------------------------------------------------------------
// fadetransition()- cross browser fade method for IE5.5+ and Mozilla/Firefox
// -------------------------------------------------------------------

ajax_ticker.prototype.fadetransition=function(fadetype, timerid){
	var contentdiv=this.contentdiv
	if (fadetype=="reset")
	this.opacitysetting=0.2
	if (contentdiv.filters && contentdiv.filters[0]){
		if (typeof contentdiv.filters[0].opacity=="number") //IE6+
			contentdiv.filters[0].opacity=this.opacitysetting*100
		else //IE 5.5
			contentdiv.style.filter="alpha(opacity="+this.opacitysetting*100+")"
	} else if (typeof contentdiv.style.MozOpacity!="undefined" && this.opacitystring!=""){
		contentdiv.style.MozOpacity=this.opacitysetting
	} else
		this.opacitysetting=1
	if (fadetype=="up")
		this.opacitysetting+=0.1
	if (fadetype=="up" && this.opacitysetting>=1)
		clearInterval(this[timerid])
}

 

Página que mostrará as mensgens (ASP)

<html>
<head>
<title>ajax_ticker - Página teste</title>
</head>
<body>
<style type="text/css">
#ajaxticker1{
	width: 200px;
	height: 100px;
	border: 1px ridge black;
	padding: 5px;
	background-color: #FEEEB8;
}

#ajaxticker1 div{ /*IE6 bug fix when text is bold and fade effect (alpha filter) is enabled. Style inner DIV with same color as outer DIV*/
	background-color: #FEEEB8;
}

.someclass{ //class to apply to your scroller(s) if desired
}

</style>
<script src="ajaxticker.js" type="text/javascript"></script>

<script type="text/javascript">

var xmlfile="teste.asp" //path to ticker txt file on your server.
new ajax_ticker(xmlfile, "ajaxticker1", "someclass", 3500, "fade")
</script>

</body>
</html>

 

Arquivo TXT com as mensagens

<div class="message">
1 - áããÇàê áããÇàê áããÇàê áããÇàê áããÇàê
</div>

<div class="message">
2 - áããÇàê áããÇàê áããÇàê áããÇàê áããÇàê
</div>

<div class="message">
3 - áããÇàê áããÇàê áããÇàê áããÇàê áããÇàê
</div>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Tá mais pra AJAX do que pra ASP!!

 

qualquer coisa a galera de JavaScript manda novamente:

 

Movido de ASP http://forum.imasters.com.br/public/style_emoticons/default/seta.gif JavaScript / DTHML

 

pelo que sei o XML é de padrão UTF-8

Compartilhar este post


Link para o post
Compartilhar em outros sites

tenta trocar esse txt por .asp e coloca isso

 

<% Response.Charset="ISO-8859-1" %>

Valeu cara, mas isso eu já havia tentado e não funcionou

 

Isto parace ser o javascript processado no cliente, tenta por dentra da tag head esta meta tag aqui

 

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

Compartilhar este post


Link para o post
Compartilhar em outros sites

tenta trocar esse txt por .asp e coloca isso

 

<% Response.Charset="ISO-8859-1" %>

Valeu cara, mas isso eu já havia tentado e não funcionou

 

Isto parace ser o javascript processado no cliente, tenta por dentra da tag head esta meta tag aqui

 

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

 

Valeu, mas também já havia adicionado esse meta-tag nas páginas envolvidas e não funcionou.

 

Por favor, se alguém tiver um tempinho, copiando esses códigos da forma como mencionei, notarão esse problema

 

Se por acaso alguém conseguir alguma solução serei extremamente grato.

Já estou arrancando todos os cabelos. Inclusive do dedão do pé.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Coloque isso no começao da página que será chamada pelo AJAX:

 

<%
Response.AddHeader "Content-Type", "text/html; charset=iso-8859-1"
response.expires=-1
%>

Caso mesmo assim não funcione, abra a página no DW, va em "Modify - Page Properties"... vá até a parte de "Ecoding" e mude para a opção "Europeu (ISO)". Salve o arquivo e pronto..

 

Abraços..

Compartilhar este post


Link para o post
Compartilhar em outros sites

Bem eu ja tive este problema e resolvi fazendo isto aqui

 

invez de usar um arquivo xml, gerei o arquivo a partir de um arquivo asp. e coloquei estas linhas de comando aqui

 

CODE
Response.Charset="ISO-8859-1"

response.ContentType = "text/xml"

 

E o xml tem que ter a tag

CODE
<?xml version=""1.0"" encoding=""iso-8859-1""?>

 

se bem que esta parte você falou que ja fez

Compartilhar este post


Link para o post
Compartilhar em outros sites

Pois é...

A solução foi alterar a extensão do arquivo de TXT para ASP e incluir

<% Response.CharSet = "ISO-8859-1" %>

 

Não consegui uma esplicação técnica, achei estranho, mas tudo bem. Resolveu

 

Valeu!

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.