如何使用jquery延迟与vktemplate /排队ajax请求 [英] how to use jquery deferred with vktemplate / queuing ajax requests

查看:98
本文介绍了如何使用jquery延迟与vktemplate /排队ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用jquery延迟时,使用 vktemplate 并不是很有效。由于vktemplate对其自己进行了ajax调用,因此在vktemplate完成其工作之前,deferred会被解析,并且它的可选回调也会被解析。我如何设置vk以便在这两件事发生之后才能解决承诺?

Using vktemplate isn't quite working when I try to use jquery deferreds. Since the vktemplate makes an ajax call of its own, the deferred gets resolved before vktemplate completes its work, and its optional callback. How can I set up vk so that the promise doesn't get resolved until after these two things happen?

$(document).on('click', '.ajax', function() {
    $.when(ajax1('<p>first</p>'), 
           ajax2('<p>second</p>'), 
           ajax3('<p>third</p>'))
     .then(function(results1, results2, results3) {
        console.log(results1);
        $('.document').append(results1);
        $('.document').append(results2); 
        $('.document').append(results3);         
        alert('all ajax done');
    });
});

function ajax1(data) {

    $.ajax({
        type: 'post',
        url: 'templates/test_template.tmpl',
        data: "data=" + data,
        dataType: 'json',
        success: function (returnedData) {

            $('#resultsDiv').vkTemplate('templates/test_template.tmpl', returnedData, function () {
                //vk callback
                //possibly call my resolve here?
            });
        }
    });
}

function ajax2(data){//more of the same}


推荐答案

由于vkTemplate不返回任何内容,您需要手动创建延迟并使用所需数据成功回调它。

Since vkTemplate returns nothing you need to manually create a deferred and resolve it in success callback with required data.

function ajax1(data) {
    var dfd = $.Deferred();

    $.ajax({
        type: 'post',
        url: 'templates/test_template.tmpl',
        data: "data=" + data,
        dataType: 'json',
        success: function (returnedData) {

            $('#resultsDiv').vkTemplate('templates/test_template.tmpl', returnedData, function (el, data, context) {
                dfd.resolveWith(context, [$(el)]);
            });
        }
    });

    return dfd.promise();
}

这篇关于如何使用jquery延迟与vktemplate /排队ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆