我有以下行动:
$('.sub_outworker').live('click', function() {
var input = $(this);
var current_div = input.parents('div.report');
var current_div_id = current_div.attr('id');
var replace_div = current_div.children('div').first();
var submission = submit_form(input, replace_div);
var i = 0;
}
submit_form()函数如下所示:
function submit_form(input, replace_div) {
var form = input.parents('form');
loading_gif(replace_div);
$.ajax({
type: 'POST',
url: form.attr('action'),
data: 'ajax=true&' + form.serialize(),
success: function(data) {
get_json();
if(data == 'success') {
return 'success';
}
else {
return 'failed';
}
}
});
}
我想检查submission ==是否失败以及它是否再次运行submit_form(即给函数第二次工作机会 - 主要是因为它因标记不匹配而偶尔会失败验证)。我不知道怎么回事!
答案 0 :(得分:2)
必须在$.ajax()
回调中完成。
$('.sub_outworker').live('click', function() {
var input = $(this);
var current_div = input.parents('div.report');
var current_div_id = current_div.attr('id');
var replace_div = current_div.children('div').first();
submit_form(input, replace_div);
}
function submit_form(input, replace_div) {
var form = input.parents('form');
loading_gif(replace_div);
$.ajax({
type: 'POST',
url: form.attr('action'),
data: 'ajax=true&' + form.serialize(),
success: function(data) {
get_json();
if(data == 'success') {
submit_form.failCount = 0;
}
else if (!submit_form.failCount) {
submit_form.failCount++;
submit_form(input, replace_div);
}
}
});
}
答案 1 :(得分:2)
如果您只是想再次运行它,那么最简单(和IMO最干净)的方式可能是使用deferred objects [docs]:
function submit_form(input, replace_div) {
var deferred = new $.Deferred();
var form = input.parents('form');
loading_gif(replace_div);
$.ajax({
type: 'POST',
url: form.attr('action'),
data: 'ajax=true&' + form.serialize(),
success: function(data) {
get_json();
if(data == 'success') {
deferred.resolve(data);
}
else {
deferred.reject(data);
}
}
});
return deferred;
}
然后你可以这样做:
var request = submit_form(input, replace_div);
request.fail(function() {
submit_form(input, replace_div);
}).done(function() {
// request was successful, do something
});
延迟对象为异步调用提供了极大的灵活性,让您可以轻松地解耦代码。当然,如果您希望看到重复尝试将Ajax调用作为submit_form
函数的“功能”,或者如果您想多次重复它,那么@Matt's answer似乎更好方式。
答案 2 :(得分:0)
function submit_form_ajax(serializedData, numAttempts) {
numAttempts--;
$.ajax({
type: 'POST',
url: form.attr('action'),
data: 'ajax=true&' + serializedData,
success: function(data) {
get_json();
if(data !== 'success') {
if( numAttempts >= 1 ) {
submit_form_ajax(serializedData, numAttempts-1);
}
}
}
});
}
function submit_form(input, replace_div) {
var form = input.parents('form');
loading_gif(replace_div);
submit_form_ajax(form.serialize(), 2);
}