JavaScript/Ajax: mudanças entre as edições
imported>Seduardo Sem resumo de edição |
imported>Guiwp (Facilitando a leitura de wikitexto.) |
||
(24 revisões intermediárias por 12 usuários não estão sendo mostradas) | |||
Linha 1: | Linha 1: | ||
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 == | == Atributos == | ||
{|border="1" cellspacing="0" cellpadding=" | |||
{|border="1" cellspacing="0" cellpadding="2" | |||
!width="100"|Nome||Descrição | !width="100"|Nome||Descrição | ||
|- | |- | ||
||readyState | ||readyState | ||
||Representa o estado do objeto, pode ser :<br> | ||Representa o estado do objeto, pode ser :<br> | ||
* 0 - não inicializado (uninitialized) | |||
* 1 - carregando (loading) | |||
* 2 - carregado (loaded) | |||
* 3 - interativo (interactive) | |||
* 4 - completo (complete) | |||
|- | |- | ||
||responseXML | ||responseXML | ||
||Resposta em xml (document) | ||Resposta em xml (document) | ||
|- | |||
||responseText | |||
||Resposta em texto | |||
|- | |- | ||
||status | ||status | ||
Linha 23: | Linha 26: | ||
||Texto de status | ||Texto de status | ||
|- | |- | ||
|| | ||multipart | ||
|| | ||Indica que esta recebendo um texto multipart | ||
|} | |} | ||
== Métodos == | == Métodos == | ||
{|border="1" cellspacing="0" cellpadding=" | |||
{|border="1" cellspacing="0" cellpadding="2" | |||
!|Nome||Descrição | !|Nome||Descrição | ||
|- | |- | ||
|| | ||abort() | ||
|| | ||Pára a transferência | ||
|- | |- | ||
|| | ||getAllResponseHeaders() | ||
||Retorna nomes dos cabeçalhos | ||Retorna nomes dos cabeçalhos | ||
|- | |- | ||
|| | ||getResponseHeader(name) | ||
||Retorna valor do cabeçalho | ||Retorna valor do cabeçalho | ||
|- | |- | ||
Linha 47: | Linha 52: | ||
||setRequestHeader("nome", "valor") | ||setRequestHeader("nome", "valor") | ||
||Atribui dados a cabeçalho antes do envio | ||Atribui dados a cabeçalho antes do envio | ||
|- | |||
||overrideMimeType("mime-type") | |||
||sobre escreve o tipo retornado | |||
|} | |} | ||
---- | == Eventos == | ||
< | |||
{|border="1" cellspacing="0" cellpadding="2" | |||
!width="100"|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. | |||
|} | |||
<br> | |||
=== Exemplo de Uso === | |||
Salve este codigo como request.js | |||
<syntaxhighlight lang="javascript" style="max-height:200px;overflow:auto"> | |||
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"); | |||
} | |||
</syntaxhighlight> | |||
Inclua na página, o seguinte comando para incluir este arquivo : | |||
<syntaxhighlight lang="javascript" style="max-height:200px;overflow:auto"> | |||
<script type="text/javascript" src="request.js"></script> | |||
</syntaxhighlight> | |||
Em seguida, você pode utilizar o código, como por exemplo, carregando um texto de forma síncrona / | |||
<syntaxhighlight lang="javascript" style="max-height:200px;overflow:auto"> | |||
var req = new RequestObject(); | |||
alert(req.loadText("textoqualer.txt")); | |||
</syntaxhighlight> | |||
Podemos também carregar numa matriz e processar linha a linha: | |||
<syntaxhighlight lang="javascript" style="max-height:200px;overflow:auto"> | |||
var req = new RequestObject(); | |||
var matriz = req.loadLines("textoqualer.txt"); | |||
for(var i=0; i < matriz.length; i++) { | |||
alert(i + ":" + matriz[i]); | |||
} | |||
</syntaxhighlight> | |||
Também é possível carregar de forma assincrona : | |||
<syntaxhighlight lang="javascript" style="max-height:200px;overflow:auto"> | |||
var req = new RequestObject(); | |||
req.bind({ | |||
url:"textoqualquer.txt", | |||
onload:function(rq, id) { | |||
alert(rq.responseText); | |||
} | |||
}); | |||
</syntaxhighlight> | |||
É possível também verificar se ocorreu algum erro, da seguinte forma : | |||
<syntaxhighlight lang="javascript" style="max-height:200px;overflow:auto"> | |||
var req = new RequestObject(); | |||
req.bind({ | |||
url:"textoqualquer.txt", | |||
onload:function(rq, id) { | |||
alert(rq.responseText); | |||
}, | |||
onerror:function(rq, id, msg) { | |||
alert('erro = ' + msg); | |||
} | |||
}); | |||
</syntaxhighlight> | |||
{{AutoCat}} |
Edição atual tal como às 23h21min de 16 de janeiro de 2014
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
Nome | Descrição |
---|---|
readyState | Representa o estado do objeto, pode ser :
|
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
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
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
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);
}
});