jQuery AJAXにおけるイベント実行順序
jQuery AJAXリクエストでは以下の順序でイベントが発生します:
- ajaxStart(グローバルイベント)
- beforeSend
- ajaxSend(グローバルイベント)
- success
- ajaxSuccess(グローバルイベント)
- error
- ajaxError(グローバルイベント)
- complete
- ajaxComplete(グローバルイベント)
- ajaxStop(グローバルイベント)
基本イベントの動作検証
$("#accountSelector").on('change', function() {
const accountCode = $(this).val();
let apiEndpoint = "";
switch(accountCode) {
case "TYPE_A":
apiEndpoint = "ACCOUNT_TYPE_A";
break;
case "TYPE_B":
apiEndpoint = "ACCOUNT_TYPE_B";
break;
default:
alert("無効な選択");
return;
}
$("#resultContainer").empty();
$.ajax({
method: "POST",
url: "/api/getOptions",
data: { category: apiEndpoint },
dataType: "json",
beforeSend: function() {
console.log("リクエスト開始前");
},
success: function(response) {
response.forEach(item => {
const option = $('<div>')
.append($('<input>', {
type: 'radio',
id: item.id,
name: 'accountOption',
value: item.value
}))
.append(item.text);
$("#resultContainer").append(option);
});
},
complete: function() {
console.log("処理完了");
}
});
});
このコード実行時、コンソールに"リクエスト開始前"が表示された後、success内の処理が実行され、最後に"処理完了"が出力されます。
グローバルイベントの検証
<script>
$(function() {
$("#loadingIndicator").ajaxStart(function() {
$(this).html("<img src='spinner.gif'>");
console.log("1. グローバル開始");
});
$("#loadButton").click(function() {
$("#contentArea").load("data.txt");
});
$("#loadingIndicator").ajaxSend(function() {
console.log("2. 送信直前");
});
$("#loadingIndicator").ajaxSuccess(function() {
console.log("3. 成功時");
});
$("#loadingIndicator").ajaxComplete(function() {
console.log("4. 完了時");
});
$("#loadingIndicator").ajaxStop(function() {
console.log("5. 全処理終了");
});
});
</script>
ボタンクリック時、コンソールに1→2→3→4→5の順で出力され、イベント順序が確認できます。