Skip to content

Instantly share code, notes, and snippets.

@jepser
Forked from stevenquiroa/xhr.js
Created June 7, 2016 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jepser/d0d718e4e9fc3004863ed95abfcf9915 to your computer and use it in GitHub Desktop.
Save jepser/d0d718e4e9fc3004863ed95abfcf9915 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){
var arr
var x = new XMLHttpRequest()
function buildQuery(url, data){
var ret = [];
for (var d in data) ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
var query = ret.join("&")
return (query) ? url + '?' + query : url;
}
if (method == 'get' || method == 'GET') {
arr = new FormData()
url = buildQuery(url, data);
}else{
if (form) arr = new FormData(form);
//Agrega los campos al request
for (d in data) arr.append(d, data[d]);
}
//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;
}
//Cuando termina si no devuelve un estado 200 o 201 hay algún error
status = true
if (x.status === 200 || x.status === 201){
//callback(error, respuesta)
status = false
}
if (typeof callback == 'function') {
callback.call(status, x.response)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment