简体   繁体   English

调用AJAX后返回函数内容

[英]Returning function content after AJAX call

I'm using webuiPopover plugin, to set popover content, i'm using a function 我正在使用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?

    }
});

Now... I can do any kind of things inside this callback. 现在...我可以在此回调中执行任何操作。 But what if I want to make another AJAX request inside this function (in this case i want to download Mustache template so i can render it with requestData and THEN return its output from the function 但是,如果我想在此函数内发出另一个AJAX请求(在这种情况下,我想下载Moustache模板,以便可以使用requestData进行渲染,然后从函数返回其输出怎么办?

I tried something like this 我尝试过这样的事情

 content:  function(requestData) {

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

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

   return template;
}

Without any luck. 没有任何运气。 How to do it correctly? 如何正确做? I know i could just set async to false, but it isn't "the right way". 我知道我可以将async设置为false,但这不是“正确的方法”。

Looking at this plugin API, I can't see the way to do what you want. 看着这个插件API,我看不到做你想要的方法。 There is async.before and async.after properties. 有async.before和async.after属性。 You can try to use them, also you can try to call setContent mannually after second request is done, like 您可以尝试使用它们,也可以尝试在第二次请求完成后手动调用setContent,例如

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

But i'm not sure if it will work. 但我不确定是否会奏效。

Newbie mistake :) Javascript is asynchronous ! 新手错误:) Javascript是异步的

What's wrong with your code : 您的代码有什么问题:

$.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.

What you should do : 您应该做什么:

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

Or even simpler : 甚至更简单:

$.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