好的,我假设有一个 AJAX 发布整个表单,看起来像这样:
/* attach a submit handler to the form */
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
term = $form.find( 'input[name="s"]' ).val(),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { s: term } );
/* Put the results in a div */
posting.done(function( data ) {
var content = $( data ).find( '#content' );
$( "#result" ).empty().append( content );
});
});
您所做的就是在函数之外添加一个变量,例如:
var started = false;
/* attach a submit handler to the form */
$("#searchForm").submit(function(event) {
if(!started)
{
started = true;
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
term = $form.find( 'input[name="s"]' ).val(),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { s: term } );
/* Put the results in a div */
posting.done(function( data ) {
var content = $( data ).find( '#content' );
$( "#result" ).empty().append( content );
});
started = false;
}
});
然后它会在再次 ajaxing 之前检查它是否首先运行,记住在完成后将 start 设置为 false。