JavaScript/Ajax

Origem: Wikilivros, livros abertos por um mundo aberto.

Com o advento do AJAX, este objeto se torna cada vez mais importante. Ele, infelizmente, não é padronizado, e portanto, até que saia uma resolução, devemos sempre fazer checagem para criação deste objeto, a seguir apresento a sua estrutura, e em seguida uma pequena rotina para criação e manipulação do mesmo.

Atributos[editar | editar código-fonte]

Nome Descrição
readyState Representa o estado do objeto, pode ser :
  • 0 - não inicializado (uninitialized)
  • 1 - carregando (loading)
  • 2 - carregado (loaded)
  • 3 - interativo (interactive)
  • 4 - completo (complete)
responseXML Resposta em xml (document)
responseText Resposta em texto
status Valor numero de retorno
statusText Texto de status
multipart Indica que esta recebendo um texto multipart

Métodos[editar | editar código-fonte]

Nome Descrição
abort() Pára a transferência
getAllResponseHeaders() Retorna nomes dos cabeçalhos
getResponseHeader(name) Retorna valor do cabeçalho
open("metodo", "url"[, indicadorDeAssincrono[, nomeUsuario [, senha]]]) Abre comunicação
send(content) Envia conteúdo
setRequestHeader("nome", "valor") Atribui dados a cabeçalho antes do envio
overrideMimeType("mime-type") sobre escreve o tipo retornado

Eventos[editar | editar código-fonte]

Nome Descrição
onload Event listener que recebe event como parametro, assim pode-se receber elementos como resposta
onerror Evento chamado caso ocorra um erro na carga
onprogress Evento chamado durante a carga, caso seja um conteudo muito grande para baixar.
onreadystatechange Evento chamado quando o estado da carga muda.


Exemplo de Uso[editar | editar código-fonte]

Salve este codigo como request.js

  var RequestObject;

  function initRequest(newRequestFunc, noBody) {
	var _newRequest = newRequestFunc;
	var _noBody = noBody;
	var _id = 0;
	return function() {
		this.newRequest = _newRequest;
		this.concatTimer = function(url, id) {
			return url +
			  (url.indexOf("?") < 0 ? "?" /"&")+
			  "requestTime=" + new Date().getTime() +
			  "&requestId=" + id;
		}
		this.loadText = function(url, method) {
			var req = _newRequest();
			req.open(method || "GET", this.concatTimer(url, _id++), false);
			if (_noBody)
				req.send();
			else
				req.send(null);
			return req.responseText;
		}
		this.splitLines = function(text) {
			try {
				return text.split(/\r?\n|\r/);
			} catch(e) {
				return [];
			}
		}
		this.loadLines = function(url, method) {
			return this.splitLines(this.loadText(url, method || "GET"));
		}
		this.loadXML = function(url, method) {
			var req = _newRequest();
			req.open(method || "GET", this.concatTimer(url, _id++), false);
			if (_noBody)
				req.send();
			else
				req.send(null);
			return req.responseXML;
		}
		this.bind = function(object) {
			var url = object['url'];
			if (typeof url == 'undefined')
				throw "necess?rio URL para fazer bind";
			var id = _id++;
			var req = _newRequest();
			var method = object['method'] || "GET";
			var headers = object['header'];
			var body = object['body'];
			var user = object['username'];
			var pass = object['password'];
			var onload = object['onload'];
			var onerror = object['onerror'];
			var onprocess = object['onprocess'];
			var onstatechange = object['onstatechange'];

			req.onreadystatechange=function() {
				if (onstatechange)
					onstatechange(req, id);
				switch(req.readyState) {
					case 0/// UNINITIALIZED open() não foi chamado ainda
						break;
					case 1/// LOADING send() não foi chamado ainda
					case 2/// LOADED send() foi chamado, disponível getResponseHeader e status
					case 3/// INTERACTIVE carregando, responseText tem dados parciais
						if (onprocess)
							onprocess(req, id);
						break;
					case 4/// COMPLETED, todas as operações foram concluidas
						if (onprocess)
							onprocess(req, id);
						if (req.status == 0 || req.status == 200) {
							if (onload)
								onload(req, id);
						} else {
							if (onerror)
								onerror(req, id, req.statusText);
						}
						break;
				}
			}
			if (user)
				req.open(method, this.concatTimer(url, id), true, user, password);
			else
				req.open(method, this.concatTimer(url, id));
			req.setRequestHeader('requestid', id);
			for(var header in headers) {
				req.setRequestHeader(header, headers[header]);
			}
			try {
				if (body && _noBody) {
					req.send();
				} else {
					req.send(body);
				}
			} catch(e) {
				if (onerror) {
					onerror(req, id, e);
				}
			}
		}
	}
  }

  if (window.ActiveXObject) {
	var objectNames = [
			"Msxml2.XMLHTTP.5.0",
			"Msxml2.XMLHTTP.4.0",
			"MSXML2.XMLHTTP.3.0",
			"MSXML2.XMLHTTP",
			"Microsoft.XMLHTTP"
        ];
	for(var i=0; i < objectNames.length; i++) {
		try {
			var requestName = objectNames[i];
			new ActiveXObject(requestName);
			RequestObject = initRequest(function() { return new ActiveXObject(requestName); }, true);
		} catch(e) {
		}
	}
  }

  if (! RequestObject && window.XMLHttpRequest) {
	try {
		new XMLHttpRequest();
		RequestObject = initRequest(function() { return new XMLHttpRequest(); }, false);
	} catch(e) {
	}
  }

  if (! RequestObject) {
	alert("Seu browser não esta preparado para o ajax");
  }

Inclua na página, o seguinte comando para incluir este arquivo :

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

Em seguida, você pode utilizar o código, como por exemplo, carregando um texto de forma síncrona /

   var req = new RequestObject();
   alert(req.loadText("textoqualer.txt"));

Podemos também carregar numa matriz e processar linha a linha:

   var req = new RequestObject();
   var matriz = req.loadLines("textoqualer.txt");
   for(var i=0; i < matriz.length; i++) {
     alert(i + ":" + matriz[i]);
   }

Também é possível carregar de forma assincrona :

   var req = new RequestObject();
   req.bind({
     url:"textoqualquer.txt",
     onload:function(rq, id) {
       alert(rq.responseText);
     }
   });

É possível também verificar se ocorreu algum erro, da seguinte forma :

   var req = new RequestObject();
   req.bind({
     url:"textoqualquer.txt",
     onload:function(rq, id) {
       alert(rq.responseText);
     },
     onerror:function(rq, id, msg) {
       alert('erro = ' + msg);
     }
   });