javascript - AJAX 完成对象字面量后执行函数

标签 javascript jquery ajax

我正在尝试将数据添加到动态模式中。仅当数据添加到模型后,模态才应显示出来。我尝试使用行 $.when(Ss.pieceInfo(piece)).then(Ss.showInfo()); 来实现此目的,但似乎两个函数同时执行。什么

var Ss = {
    $modal: $('#piece-modal'),
    $title: $('.piece-title'),
    $artist: $('.piece-artist'),
    $info: $('.piece-info'),


    init: function() {
        this.bindEvents();
    },

    bindEvents: function() {
        $('.piece').on("click", function(e) {
            e.preventDefault();
            var piece = $(this).data('slug');

        //This doesn't seem to have any effect
            $.when(Ss.pieceInfo(piece)).then(Ss.showInfo());
        });
    },

    pieceInfo: function(piece) {
        console.log(piece);
        $.getJSON(Kirby.baseUrl + '/api/v1/work/' + piece, function(data) {

            $.each(data, function(key, val) { 
                Ss.$title.html(val.title);
                Ss.$artist.html(val.artist); 
                Ss.$info.html(val.text);
            })
        });
    },

    showInfo: function() {
        var height = $('.primary-info').height();
        console.log(height)
        Ss.$modal.addClass('modal-active')
        Ss.$modal.css('transform','translate3D(0, calc(100% - '+ height +'px), 0)');
    },
};

$(document).ready(function(){
    Ss.init();
});

最佳答案

这是因为您没有在 Ss.pieceInfo() 方法中返回 Promise,导致它立即得到解决。 As per the documentation for $.when() :

If a single argument is passed to jQuery.when() and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.

为此,您只需稍微更改该方法:返回 $.getJSON promise 。

pieceInfo: function(piece) {
    return $.getJSON(Kirby.baseUrl + '/api/v1/work/' + piece, function(data) {

        $.each(data, function(key, val) { 
            Ss.$title.html(val.title);
            Ss.$artist.html(val.artist); 
            Ss.$info.html(val.text);
        })
    });
},

关于javascript - AJAX 完成对象字面量后执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46240308/

相关文章:

javascript - 使部分contentEditable无法删除

asp.net - 如何保护 ajax 处理程序的安全?

javascript - 打开的网络套接字连接是否阻止了 ajax 请求?

javascript - 使用 Web 表单替换 Javascript 变量

jquery - 根据页面宽度实时更改 CSS

jQuery 移动 ajax 导航

javascript - HTML5 音频输出修补

javascript - 元素在 ipad 上的 safari 中消失

javascript - 如何比较innerHTML(JavaScript中的字符串比较)

javascript - 无法将新寄存器发送到我的数据库 mongodb