簡體   English   中英

調用AJAX后返回函數內容

[英]Returning function content after AJAX call

我正在使用webuiPopover插件來設置彈出內容,我正在使用一個函數

$('.blob a').webuiPopover({
    template: template,
    trigger: 'hover',
    type: 'async',
    url: '/ajax/getprofileinfo.php?user=433',
    content:  function(requestData) {
          //executed after successful ajax request. 
         //How I can make another ajax call and then return everything to content?

    }
});

現在...我可以在此回調中執行任何操作。 但是,如果我想在此函數內發出另一個AJAX請求(在這種情況下,我想下載Moustache模板,以便可以使用requestData進行渲染,然后從函數返回其輸出怎么辦?

我嘗試過這樣的事情

 content:  function(requestData) {

     var template = '';
     $.get('/tpl/usertemplate.mustache').done(function(templateData) {

         template = Mustache.render(templateData, requestData);
     });

   return template;
}

沒有任何運氣。 如何正確做? 我知道我可以將async設置為false,但這不是“正確的方法”。

看着這個插件API,我看不到做你想要的方法。 有async.before和async.after屬性。 您可以嘗試使用它們,也可以嘗試在第二次請求完成后手動調用setContent,例如

content:  function(requestData) {
    vat that = this;
    $.get(url).done(function (data){
        that.setContent(Mustache.render(templateData, data));
    });
}

但我不確定是否會奏效。

新手錯誤:) Javascript是異步的

您的代碼有什么問題:

$.get('/tpl/usertemplate.mustache').done(function(templateData) { // This is done FIRST
     template = Mustache.render(templateData, requestData); // This is done whenever the GET is finished, so... THIRD
});
return template; // This is done SECOND - At this point, template is empty.

您應該做什么:

$.get('/tpl/usertemplate.mustache').done(function(templateData) {
     template = Mustache.render(templateData, requestData);
     return template;
});

甚至更簡單:

$.get('/tpl/usertemplate.mustache').done(function(templateData) {
     return Mustache.render(templateData, requestData);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM