編集:
最近これに賛成票を投じたので、もうこのやり方はしないと言わざるを得ません。$.ajax
を返すpromise
ので、Promise を直接使用して、ここで行ったことのほとんどをより一貫性のある堅牢な方法で行うことができます。
function customRequest(u,d) {
var promise = $.ajax({
type: 'post',
data: d,
url: u
})
.done(function (responseData, status, xhr) {
// preconfigured logic for success
})
.fail(function (xhr, status, err) {
//predetermined logic for unsuccessful request
});
return promise;
}
次に、使用法は次のようになります。
// using `done` which will add the callback to the stack
// to be run when the promise is resolved
customRequest('whatever.php', {'somekey': 'somevalue'}).done(function (data) {
var n = 1,
m = 2;
alert(m + n + data);
});
// using fail which will add the callback to the stack
// to be run when the promise is rejected
customRequest('whatever.php', {'somekey': 'somevalue'}).fail(function (xhr, status, err) {
console.log(status, err);
});
// using then which will add callabcks to the
// success AND failure stacks respectively when
// the request is resolved/rejected
customRequest('whatever.php', {'somekey': 'somevalue'}).then(
function (data) {
var n = 1,
m = 2;
alert(m + n + data);
},
function (xhr, status, err) {
console.log(status, err);
});
確かに私はこれをいつもやっています。実際の成功コールバック内でコールバックを実行するか、コールバックを成功コールバックとして割り当てることができます。
function customRequest(u,d,callback) {
$.ajax({
type: "post",
url: u,
data:d,
success: function(data) {
console.log(data); // predefined logic if any
if(typeof callback == 'function') {
callback(data);
}
}
});
}
使用法は次のようになります。
customRequest('whatever.php', {'somekey': 'somevalue'}, function (data) {
var n = 1,
m = 2;
alert(m + n + data);
});