AJAX 响应未在 JavaScript 模板中呈现

AJAX response not rendering in JavaScript template

我有以下 jQuery AJAX 请求,returns 正确的 JSON 响应,正如预期的那样(这是一个 youtube ID)。但是,当我尝试使用以下方法将 ytid 插入 framecode 时:

rendered = Mustache.render(framecode, {ytid: ytid});

我剩下一个空的 space,其中 {{ytid}} 应该替换为 ytid 的内容。 在 firefox 调试器中,ytid 显示为预期的字符串,当我在调试器中 运行 上面的行时,{{ytid}} 被预期的替换为 youtube id。很奇怪。另外,当我打印 ytid 到控制台时,它也打印正确,所以我确定变量不为空。

$(document).on("click", ".movlist_youtubebutton", function() {
    console.log("Youtube Button Clicked");
    var ytid = $(this).data('ytid');
    var movid = $(this).data('movid');

    function isEmpty(str) {
        return (!str || 0 === str.length);
    }

    if (isEmpty(ytid)) {
        $.ajax({
            url: "/gettrailer/",
            method: "GET",
            data: {movid: movid},
            dataType: "json",
            success: function (result) {
                console.log(result);
                    ytid = result.ytid;
                    window.ytid = ytid;
                    console.log(ytid);
            }
        });
    }
    framecode = '<iframe width="560" height="315" src="https://www.youtube.com/embed/{{ytid}}" frameborder="0" allowfullscreen></iframe>';
    rendered = Mustache.render(framecode, {ytid: ytid});
    console.log(rendered);
    // window.ytid = 'test3'
    console.log(ytid);
    popup = $('#popup' + movid);
    popup.popup({
        opacity: 0.3,
        transition: 'all 0.3s'
    });
    popup.popup('show');
    popup.html(rendered);
});

这是因为 $.ajax 调用是异步的,所以它在 framecode 已经分配后完成。您需要将其余代码包装在 $.ajax 之后的 .then 中以解决此问题。

这是针对 Stephen 的回答编辑的工作代码

function isEmpty(str) {
    return (!str || 0 === str.length);
}

function framereplace(ytid, movid) {
    framecode = '<iframe width="560" height="315" src="https://www.youtube.com/embed/{{ytid}}" frameborder="0" allowfullscreen></iframe>';
    rendered = Mustache.render(framecode, {ytid: ytid});
    popup = $('#popup' + movid);
    popup.popup({
        opacity: 0.3,
        transition: 'all 0.3s'
    });
    popup.popup('show');
    popup.html(rendered);
}

$(document).on("click", ".movlist_youtubebutton", function() {
    console.log("Youtube Button Clicked");
    var ytid = $(this).data('ytid');
    var movid = $(this).data('movid');

    if (isEmpty(ytid)) {
        $.ajax({
            url: "/gettrailer/",
            method: "GET",
            data: {movid: movid},
            dataType: "json",
            success: function (result) {
                console.log(result);
                ytid = result.ytid;
            }
        }).then(framereplace(ytid, movid)); // needs to happen after
    } else {
        framereplace(ytid, movid);
    }
});