我一直在研究jQueryAjax队列系统。我有一个逐步发电机。它生成一个pdf,然后一旦生成pdf,就会创建一个图像。一旦这两个过程完成,我就会发送一封电子邮件确认。它还必须灵活地添加额外的步骤。
然而,我还没有找到一个行之有效的例子。它们都使用"COMPLETE"而不是"success",所以如果我通过jSON返回错误,它就会被忽略。它移动到队列中的下一个
有什么想法吗?
编辑
发生的事情很复杂。
我的插件(从另一个插件复制)
$.AjaxQueue = function() {
this.reqs = [];
this.requesting = false;
};
$.AjaxQueue.prototype = {
add: function(req) {
this.reqs.push(req);
this.next();
},
next: function() {
if (this.reqs.length == 0)
return;
if (this.requesting == true)
return;
var req = this.reqs.splice(0, 1)[0];
var complete = req.complete;
var self = this;
if (req._run)
req._run(req);
req.complete = function() {
if (complete)
complete.apply(this, arguments);
self.requesting = false;
self.next();
}
this.requesting = true;
$.ajax(req);
}
};
我还写了一个函数来加快我的代码
function createQueue(file, inputid, step, params) {
var queue = new $.AjaxQueue();
queue.add({
url: file,
type: 'POST',
dataType: "json",
data: params,
complete : function(data, status) {
$('li#step' + step + ' .loading').remove();
// DO SOMETHING. CANT CHECK FOR ERRORS
},
success : function(data, status) {
// DOES NOT WORK
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "nError:" + err);
},
_run: function(req) {
//special pre-processor to alter the request just before it is finally executed in the queue
//req.url = 'changed_url'
$('li#step' + step).append('<span class="loading"></span>');
}
});
}
步骤1。我正在使用mpdf生成pdf。现在这需要几秒钟的时间来实际构建,这取决于主题、使用的图像等。所以我称之为:
createQueue('post_pdf.php', id, 1, { 'filename': filename + '.pdf', 'id': id, 'crop': crop } );
步骤2-生成一些图像
createQueue('ajax_image.php', id, 2, { 'filename': filename + '.pdf' } );
步骤3-(其他类似发送电子邮件摘要的东西)
createQueue('mail.php', id, 3, { 'from': 'newfilename', 'to': 'emavle@pb.com', 'subject': 'This is a subject', 'body': 'Body Copy' } );
如果它在步骤1失败,我可以在控制台中看到它,但它没有返回
正如@charlietfl所建议的,在服务器端使用PHP中的每一步。AJAX调用完成后,您可以从服务器获得响应,并在此基础上继续。示例:
// make AJAX request to file.php and send 'data'
var request = $.ajax({
url: "file.php",
type: "POST",
data: { data }
});
// when PHP is done, receive the output and act accordingly
request.done(function( msg ) {
if (msg == "A") {
// plan A
} else if (msg == "B") {
// plan B
}
});