ブートストラップと JQuery を使用しています。「$.ajax beforeSend」で ajax 呼び出しを行う前に、ブートストラップ モーダル ダイアログを呼び出すことができるかどうかを知りたいですか? フォームを送信する前にユーザーのコメントを収集したい。この動作を必要とするボタンがページにいくつかあります。だから、私はそれをもっと一般的にしたいと思っています。
ありがとう
ブートストラップと JQuery を使用しています。「$.ajax beforeSend」で ajax 呼び出しを行う前に、ブートストラップ モーダル ダイアログを呼び出すことができるかどうかを知りたいですか? フォームを送信する前にユーザーのコメントを収集したい。この動作を必要とするボタンがページにいくつかあります。だから、私はそれをもっと一般的にしたいと思っています。
ありがとう
jQuery のDeferred
オブジェクトの使用をお勧めします ( http://api.jquery.com/category/deferred-object/を参照)。以下は、ボタンのイベント ハンドラーの擬似コードです。
$('#theButton').on('click', function() {
var dfd = $.Deferred();
// Code to show modal dialog here.
// Pass dfd to the dialog, and have it call dfd.resolve()
// when the user has finished, or dfd.reject() in case the
// user does not complete the form.
dfd.done(function() {
// Ajax call here
});
});
引数として渡される関数は、誰かがDeferred オブジェクトdfd.done()
のメソッドを呼び出した場合にのみ呼び出されます。resolve()
Due to the asynchronous event model in javascript, you cannot postpone the ajax request from being sent off from within beforeSend
. Once beforeSend
is executed, the only chance you have to "delay" the ajax request is to outright cancel it entirely by returning false from the callback.
So while you could keep track of a status variable that knows whether the form is ready to submit (return false from beforeSend
whenever the form is not ready), you're much better off doing these validation checks before ever creating the ajax request to begin with.
// why do this
$.ajax('/path', {
beforeSend: function () {
if (formIsNotReady()) {
showModal();
return false;
}
}
});
// when you can do this
if (formIsNotReady()) {
showModal();
} else {
$.ajax('/path');
}