Skip to content

Instantly share code, notes, and snippets.

@stevenquiroa
Last active June 8, 2016 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stevenquiroa/b5b99771076bc84850cffe4020d27907 to your computer and use it in GitHub Desktop.
Save stevenquiroa/b5b99771076bc84850cffe4020d27907 to your computer and use it in GitHub Desktop.
Función xhr para hacer llamadas ajax
//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)
}
}
}
@jepser
Copy link

jepser commented Jun 7, 2016

@stevenquiroa
Copy link
Author

@jepser maybe

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment