3
I like encapsulation because it greatly reduces the source code, I have done the following about ajax:
custom.ajax=function(obj,funcao,view){ // FUNÇÃO AJAX
var data = {'obj':obj,'funcao':funcao}; // SETA OS PARAMETROS
var retorno; // VAR DE RETORNO
$.ajax({type:"POST", url:view, dataType:"json", data:data,async:false, // FAZ UM AJAX SINCRONIZADO COM A FUNCAO
success: function(json) { retorno = json; }, // RETORNO DO AJAX NO SUCCESS
error: function(json) { retorno=json; }, // RETORNO DO AJAX NO ERROR
beforeSend: function() { $('body').css('cursor','wait'); }, // RETORNO DO AJAX NO ERROR
complete: function(){ $('body').css('cursor','default'); }
}); // FIM DO AJAX
return retorno; // RETORNO DA FUNÇÃO
};
With this code every time I want to do an ajax I use only 1 line of code passing my parameters like this:
var r = custom.ajax(new Object(),'getConhecimentos','../view/cobranca/vRelacaoCobranca.php');
preencherTela(r); // para preencher o HTML.
The problem of this technique is that my page is waiting for ajax to complete, ie the part of asynchronous in the parameter case async:true would be the solution, the problem is that I would have to write the whole ajax every time, would not have a way to encapsulate? because the rest of the programming would be inside the parameter Success in this way:
var funcao = 'getConhecimentos';
var obj = new Object();
var data = {'obj':obj,'funcao':funcao}; // SETA OS PARAMETROS
var view = '../view/cobranca/vRelacaoCobranca.php';
$.ajax({type:"POST", url:view, dataType:"json", data:data,async:true, // FAZ UM AJAX SINCRONIZADO COM A FUNCAO
success: function(json) { relCob.tableStyle(json,'jqxGrid-conhec'); }, // RETORNO DO AJAX NO SUCCESS
error: function(json) { console.log(json) }, // RETORNO DO AJAX NO ERROR
beforeSend: function() { $('body').css('cursor','wait'); }, // RETORNO DO AJAX NO ERROR
complete: function(){ $('body').css('cursor','default'); }
});
My question is: would you have some way to encapsulate the ajax and keep it asynchronously? (async:true)
solved with the promise, I do not know why with the callback did not work, I think until I had tried once with the callback and had not succeeded, but the promise already resolves me here thanks!
– SneepS NinjA