【问题标题】:Prevent script execution until function has finished在函数完成之前阻止脚本执行
【发布时间】:2016-06-20 11:00:41
【问题描述】:

我正在动态添加一个 Input type="text":

elements.prepend('<input type="text" class="data form-control searchText" placeholder="'+lang(452)+'" />');

在占位符中,调用函数“lang()”,从我们的数据库中为每种语言获取正确的占位符:

function lang(id){
    $.post('gallery.php',{lang:id}).done(function(data){return data});
}

现在占位符总是显示“未定义”,因为脚本似乎在 $.post 获得 ReadyState 4 之前已经完成。

有人知道如何做到这一点吗? 还是有更好的想法?

谢谢

【问题讨论】:

    标签: ajax wait .post


    【解决方案1】:

    通过使用 $.ajax 函数并将 async 设置为 false 发现它可以工作:

    function lang(id){
        txt = '';
        $.ajax({url:'gallery.php', type:"POST", async:false, data:{lang:id}}).success(function(data){txt = data});
        return txt;
    }
    

    注意: 仅当 url 指向本地脚本时,异步才有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-06
      • 2013-02-17
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多