Last active
June 8, 2016 17:52
-
-
Save stevenquiroa/b5b99771076bc84850cffe4020d27907 to your computer and use it in GitHub Desktop.
Función xhr para hacer llamadas ajax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//funcion para hacer las llamadas ajax | |
function xhr (method, url, data, form, callback){ | |
console.log('xhr') | |
var arr = new FormData() | |
if (method == 'get' || method == 'GET') { | |
var ret = []; | |
for (var d in data) ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d])); | |
var query = ret.join("&") | |
if (query) url = url + '?' + query; | |
}else{ | |
if (form) arr = new FormData(form); | |
//Agrega los campos al request | |
for (d in data) arr.append(d, data[d]); | |
} | |
var x = new XMLHttpRequest() | |
//Abre el request | |
x.open(method, url, true) | |
//Coloca el tipo de respuesta que se espera recibir | |
x.responseType = "json" | |
//Envia el request con los campos | |
x.send(arr) | |
//Se espera la respuesta | |
x.onreadystatechange = function(){ | |
//Si no esta en un estado 4 no pasa (4 == DONE) | |
if (x.readyState != 4) { | |
// console.log('Esperando...', x.response, x.readyState, x.status) | |
return; | |
} | |
console.log('Termino y lanzo:', x.response, x.readyState, x.status) | |
//Cuando termina si no devuelve un estado 200 o 201 hay algún error | |
if (x.status === 200 || x.status === 201){ | |
//callback(error, respuesta) | |
callback(false, x.response) | |
} else if(x.readyState == 4){ | |
callback(true, x.response) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Maybe? https://gist.github.com/jepser/d0d718e4e9fc3004863ed95abfcf9915