Eu já postei uma tentativa minha de melhorar a vida de alguns desenvolvedores que aparecem no fórum com dificuldades de executar ajax.
O post era : Interface Ajax, Código pronto para executar ajax.
Tentando melhorar e facilitar, eu acho que dificultei rsrsrs. Bom, amadureci a idéia e utilizei alguns conceitos de encapsulamento que aprendi do jQuery e usei nesse outro código.
Na maioria das vezes queremos simplesmente executar o ajax, sem nos preocupar com nada não é? Então, facilitei ao invés de dificultar.
Agora não uso mais uma "Classe", mas uma função que retorna o escopo de um objeto, com seus métodos.
Então, você programador tem a opção de usar 4 atributos:
- method -> "GET" ou "POST". Padrão: "GET"
- async -> true ou false. Padrão: false
- headers -> Ex: {"content-type": "text/html"}
- cache -> true ou false . Padrão: true
cache define se quer usar cache ou não. Se não quiser usar cache defina como false.
Além desses 4 atributos, tem ainda 2 métodos:
- onchangestate(function(ajax){}) -> Objeto ajax é usado na função onchangestate e usado o escopo do objeto html (this == objeto HTML)
- callback( function(ajax){} ) -> Objeto ajax é usado na função callback e usado o escopo do objeto html (this == objeto HTML)
Estes parâmetros todos são opcionais, não obrigatórios.
Vou mostrar aqui um exemplo de funcionamento com o onchangestate, quero usar o ajax para colocar um conteúdo dentro de uma div chamada "caixa", vou adicionar também um gif na div de loading:
CODE
var obj = document.getElementById('caixa')
ajax(obj).load('conteudo.htm', {
onstatechange : function(ajax){
if(ajax.readyState == 1)
this.style.background = "url(loading.gif) no-repeat center center"
else if(ajax.readyState == 4){
this.style.background = "#fff"
this.innerHTML = ajax.responseText
}
}
})
ajax(obj).load('conteudo.htm', {
onstatechange : function(ajax){
if(ajax.readyState == 1)
this.style.background = "url(loading.gif) no-repeat center center"
else if(ajax.readyState == 4){
this.style.background = "#fff"
this.innerHTML = ajax.responseText
}
}
})
Se você quiser apenas colocar o conteúdo dentro de algum lugar, basta usar o ajax(elementoHTML).load("arquivo.ext").
Fiz um exemplo para uma situação real, quando queremos abrir um modal e seu conteúdo é carregado via ajax. Vou deixar a disposição de vocês para download.
Para quem estiver interessado no código, mas não muito pelo exemplo da modal, está aqui o código do ajax:
CODE
/*
Interface Ajax:
Desenvolvido por: Eduardo Ottaviani.
Email: edudu_tata@hotmail.com.
Licença: Pública.
Link:
"Por favor, não retire os comentários. Eles não pesarão no seu programa.
Dessa forma, caso goste do código, você e outras pessoas
poderão me localizar mais facilmente. Obrigado. =)"
*/
function ajax( obj ){ return new Ajax(obj) }
function Ajax( obj ){ this.element = obj }
Ajax.prototype.ajax = new function(){
try{
var ajax= new XMLHttpRequest()
return function(){return new XMLHttpRequest()}
}
catch(e){
try{
var ajax = new ActiveXObject("Msxml2.XMLHTTP")
return function(){return new ActiveXObject("Msxml2.XMLHTTP")}
}
catch(ee){
try{
var ajax = new ActiveXObject("Microsoft.XMLHTTP")
return function(){return new ActiveXObject("Microsoft.XMLHTTP")}
}
catch(E){alert("O navegador não suporta ajax")}
}
}
}
Ajax.prototype.load = function(url, options){
var element = this.element
var method = "GET"; var async = true; var headers = {}
var callback = function(){}; var cache = ""
if(options){
method = options.method ? options.method.toUpperCase() : method
async = options.async ? options.async : async
headers = options.headers ? options.headers : headers
callback = options.callback ? options.callback: callback
cache = (typeof options.cache!="undefined") ? options.cache? cache: Math.random() : cache
}
if ( cache ){
url = url.match(/\?/) ?
url + "&cache=" + cache :
url + "?" + cache
}
var ajax = this["ajax"]()
ajax . onreadystatechange = (options && options.onchangestate)
?function(){ options.onchangestate.call(element, ajax) }
:function(){ if(ajax.readyState == 4){ element.innerHTML = ajax.responseText; callback.call(element, ajax)} }
if( method == "GET"){
ajax.open(method, url, async)
ajax.send(null)
}
else if( method == "POST" ){
ajax.open( method, url.split("?")[0], async )
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
for(var x in headers)
ajax.setRequestHeader( x, headers[x] )
ajax.send(url.split("?")[1])
}
return this
}
Interface Ajax:
Desenvolvido por: Eduardo Ottaviani.
Email: edudu_tata@hotmail.com.
Licença: Pública.
Link:
"Por favor, não retire os comentários. Eles não pesarão no seu programa.
Dessa forma, caso goste do código, você e outras pessoas
poderão me localizar mais facilmente. Obrigado. =)"
*/
function ajax( obj ){ return new Ajax(obj) }
function Ajax( obj ){ this.element = obj }
Ajax.prototype.ajax = new function(){
try{
var ajax= new XMLHttpRequest()
return function(){return new XMLHttpRequest()}
}
catch(e){
try{
var ajax = new ActiveXObject("Msxml2.XMLHTTP")
return function(){return new ActiveXObject("Msxml2.XMLHTTP")}
}
catch(ee){
try{
var ajax = new ActiveXObject("Microsoft.XMLHTTP")
return function(){return new ActiveXObject("Microsoft.XMLHTTP")}
}
catch(E){alert("O navegador não suporta ajax")}
}
}
}
Ajax.prototype.load = function(url, options){
var element = this.element
var method = "GET"; var async = true; var headers = {}
var callback = function(){}; var cache = ""
if(options){
method = options.method ? options.method.toUpperCase() : method
async = options.async ? options.async : async
headers = options.headers ? options.headers : headers
callback = options.callback ? options.callback: callback
cache = (typeof options.cache!="undefined") ? options.cache? cache: Math.random() : cache
}
if ( cache ){
url = url.match(/\?/) ?
url + "&cache=" + cache :
url + "?" + cache
}
var ajax = this["ajax"]()
ajax . onreadystatechange = (options && options.onchangestate)
?function(){ options.onchangestate.call(element, ajax) }
:function(){ if(ajax.readyState == 4){ element.innerHTML = ajax.responseText; callback.call(element, ajax)} }
if( method == "GET"){
ajax.open(method, url, async)
ajax.send(null)
}
else if( method == "POST" ){
ajax.open( method, url.split("?")[0], async )
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
for(var x in headers)
ajax.setRequestHeader( x, headers[x] )
ajax.send(url.split("?")[1])
}
return this
}
É isso aí, espero que esse ajude melhor do que o antigo.
Lembrando que esse código é para quem não usa nenhum framework.
Estou aberto à críticas/sugestões. Quem quiser incrementar o objeto com mais métodos, fique à vontade.
Aquelabrassss