除非您进行 同步 AJAX调用(您可能不想这样做),否则您根本无法做到。
如果在您的代码中的多个位置使用了此函数,则最好的选择是允许它 接收 一个函数。
这样,您实际上是直接将代码传递进来,而不是依赖 从 函数 返回 的结果来在某些代码中使用,因此可以确保使用响应。
var my_form = $('#my_form');my_form.submit( valid_pass_sett );function valid_pass_sett() { //pre to remove errors left over from previous submissions - snipped pass_old = $('input[name=pass_old]').val(); pass_new = $('input[name=pass_new]').val(); pass_/confirm/i_new = $('input[name=pass_/confirm/i_new]').val(); validate('password', pass_new, pswd_validation_callback); // async validation return false; // cancel form submission}function validate(request_type, request_text, callback ) { $.post("http://www.example.com/ajax/validate.php",{ type: request_type, text: request_text }, callback );}function pswd_validation_callback( data ) { if ( data === 'valid' ) { // if valid, call the native .submit() instead of the jQuery one my_form[ 0 ].submit(); } else { // Otherwise do your thing for invalid passwords. // The form has already been canceled, so no concerns there. $('#pass_new').addClass('error'); $('#pass_/confirm/i_new').addClass('error'); $(error_string.format('Please enter a valid password.')).insertAfter('#pass_/confirm/i_new'); $('#pass_text_short').hide(); $('#pass_text_long').show(); }}编辑: 更改为使用有问题的代码。
编辑: 更新与发布的其他代码一起使用。 为了清楚起见,将答案缩小到命名函数。



