【问题标题】:how to use jquery deferred with vktemplate / queuing ajax requests如何使用 vktemplate 延迟的 jquery / 排队 ajax 请求
【发布时间】:2012-11-07 21:15:28
【问题描述】:

当我尝试使用 jquery deferreds 时,使用 vktemplate 并不能很好地工作。由于 vktemplate 进行了自己的 ajax 调用,所以 deferred 在 vktemplate 完成其工作和可选回调之前得到解决。我如何设置 vk 以便在这两件事发生之前不会解决承诺?

$(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}

【问题讨论】:

    标签: javascript jquery jquery-templates jquery-deferred


    【解决方案1】:

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

    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();
    }
    

    【讨论】:

    • 使用上下文和参数解决延迟问题。 api.jquery.com/deferred.resolveWith
    • 其实回调中的这些参数是从哪里来的呢? (el, data, context) 它们是 vktemplate 的一部分还是来自延迟对象?
    • 这很有趣,因为我的success 回调使用了参数returnedData,但是当我将它们打印到控制台时,returnedDatadata 都显示了相同的对象。你知道这是为什么吗?谢谢!
    • vkTemplate 传递使用if(callback) {callback(elm, jsonObj, context);}调用的数据
    猜你喜欢
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多