I have several methods that wrap the $.ajax()
method and return its jqXHR, but I need to force fail before even calling the original $.ajax()
and still allow to use success/error methods of the result.
//just a very simple example, actuall code is more complicated
$.rpc = function(method, args) {
if (!method || 'string' === typeof method ||) {
return false; //PROBLEM - cannot use success/error handlers!
}
return $.ajax({
type: 'POST',
url: '/rpc',
data: { method: method, params: args },
}); //AJAX()
};
//usage:
$.rpc(loginMethod, credentials).success(gotoProfile).fail(gotoLogin);
//if loginMethod is for any reason undefined it crash instead of calling fail handler
So I use this helper method, since the jqXHR is created directly inside the Ajax method:
$.ajax.getFailed = function(message) {
var
jqDef = new $.Deferred(),
jqXHR = jqDef.promise();
jqXHR.success = jqXHR.done; //deprecated $.ajax methods
jqXHR.error = jqXHR.fail;
jqDef.reject.defer(1, jqXHR, [jqXHR, message]);
//defer is from extJS, alternative to setTimeout
return jqXHR;
};
$.rpc = function(method, args) {
if (!method || 'string' === typeof method ||) {
return $.ajax.getFailed('Missing method');
}
return $.ajax({
type: 'POST',
url: '/rpc',
data: { method: method, params: args },
}); //AJAX()
};
Is this code OK or is there anything else I should add?
-
\$\begingroup\$ Does your approach work? If it works, I guess it is OK :) \$\endgroup\$Simon Forsberg– Simon Forsberg2015年03月11日 14:38:15 +00:00Commented Mar 11, 2015 at 14:38
-
\$\begingroup\$ I've made a jQuery plugin that supports this approach: github.com/nothrem/jQueryProcess (see the last part of the README). \$\endgroup\$Radek Pech– Radek Pech2015年03月12日 15:19:48 +00:00Commented Mar 12, 2015 at 15:19
1 Answer 1
Looking at the documentation for $.ajax
reveals a beforeSend
option that would allow you to cancel the request before it's sent by returning false
.
$.rpc = function(method, args) {
var beforeSend = function () {
return method && 'string' !== typeof method;
}
return $.ajax({
type: 'POST',
url: '/rpc',
data: { method: method, params: args },
beforeSend: beforeSend
});
};
-
\$\begingroup\$ This seems to work for fail case correctly and answers the original question. But in the meanwhile I've created similar method getDone() which I use in case the data are already cached on client - and this method cannot cancel the AJAX while calling the success handlers. \$\endgroup\$Radek Pech– Radek Pech2015年03月12日 13:47:27 +00:00Commented Mar 12, 2015 at 13:47