mirror of
https://git.imnavajas.es/jjimenez/safekat.git
synced 2025-07-25 22:52:08 +00:00
87 lines
2.2 KiB
JavaScript
87 lines
2.2 KiB
JavaScript
class Ajax {
|
|
constructor(url, data, headers, success, error, type = 'default') {
|
|
this.url = url;
|
|
this.data = data;
|
|
this.headers = headers;
|
|
this.success = success;
|
|
this.error = error;
|
|
this.type = type;
|
|
this.jqXHR = null;
|
|
}
|
|
post() {
|
|
(this.type == 'default') ? this.ajax('POST') : this.ajaxForm('POST');
|
|
}
|
|
get() {
|
|
this.ajax('GET');
|
|
}
|
|
put() {
|
|
(this.type == 'default') ? this.ajax('PUT') : this.ajaxForm('PUT');
|
|
}
|
|
delete() {
|
|
(this.type == 'default') ? this.ajax('DELETE') : this.ajaxForm('DELETE');
|
|
}
|
|
abort() {
|
|
if (this.jqXHR) {
|
|
this.jqXHR.abort();
|
|
this.jqXHR = null; // Limpiamos la referencia a la petición
|
|
}
|
|
}
|
|
setData(data) {
|
|
this.data = data;
|
|
}
|
|
ajax(method) {
|
|
if (this.jqXHR) {
|
|
this.jqXHR.abort();
|
|
}
|
|
|
|
this.jqXHR = $.ajax({
|
|
url: this.url,
|
|
type: method,
|
|
data: this.data,
|
|
headers: this.headers,
|
|
success: this.success,
|
|
error: this.error
|
|
})
|
|
}
|
|
ajaxForm(method) {
|
|
if (this.jqXHR) {
|
|
this.jqXHR.abort();
|
|
}
|
|
|
|
this.jqXHR = $.ajax({
|
|
url: this.url,
|
|
type: method,
|
|
data: this.data,
|
|
processData: false,
|
|
contentType: false,
|
|
headers: this.headers,
|
|
success: this.success,
|
|
error: this.error
|
|
})
|
|
}
|
|
|
|
getPromise() {
|
|
if (this.jqXHR) {
|
|
this.jqXHR.abort();
|
|
}
|
|
|
|
return new Promise((resolve, reject) => {
|
|
this.jqXHR = $.ajax({
|
|
url: this.url,
|
|
type: 'GET',
|
|
data: this.data,
|
|
headers: this.headers,
|
|
success: (response) => {
|
|
if (this.success) this.success(response);
|
|
resolve(response);
|
|
},
|
|
error: (xhr) => {
|
|
if (this.error) this.error(xhr);
|
|
reject(xhr);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
}
|
|
|
|
export default Ajax |