javascript - jQuery $.post() 请求除非运行两次否则不起作用

标签 javascript jquery ajax function

这里有两个函数。

function getUserInformation(UserID) {
    $.post("assets/scripts/chat/get_user_info.php", {
        UserID: UserID
    }, function (data) {
        if (data == "error") {
            alertBar('negative', 'There was an error sending the message');
        }
        window.username = data;
    })
}

function CreateChatBox(UserID) {
    if ($('#' + UserID).length == 0) {
        getUserInformation(UserID);
        alert(username);
    }

我的问题是,当 CreateChatBox()函数执行后,必须单击两次才能实际工作。如果我删除 getUserInformation() 怎么办?函数来自 CreateChatBox()功能CreateChatBox()函数执行成功。

有人可以帮我解决这个问题吗?谢谢。

---编辑(额外细节)----

当我点击链接时 <a onclick = "CreateChatBox()">Some link</a>什么都没发生。但当我第二次点击它时,它确实起作用了。如果我删除函数 getUserInformation()来自CreateChatBox()功能CreateChatBox()单击链接时,该功能首次运行。

最佳答案

这是因为您没有等待ajax响应完成。当您第一次单击时,ajax 调用是通过 post 进行的,第二次单击时,响应很可能可用,因此您可以获得它。您可以看到这将警报放入成功处理程序中。

function getUserInformation(UserID) {
   $.post("assets/scripts/chat/get_user_info.php", 
   {
         UserID: UserID
   }, 
   function(data){
         if (data == "error") {
             alertBar('negative','There was an error sending the message');
         }
         window.username = data;
         alert(window.username);
   });
}


function CreateChatBox(UserID) {
   if ($('#'+UserID).length==0) {
        getUserInformation(UserID);
   }
   //alert(username);
}

关于javascript - jQuery $.post() 请求除非运行两次否则不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8945854/

相关文章:

javascript - 在选项卡完全关闭时保持 setInterval 运行

javascript - 从函数中使用 iframe 打开 fancybox 弹出窗口

javascript - 当我追加到数组时,Ractive.js 会追加还是重建所有内容?

javascript - 如何通过 jQuery AJAX 从使用 OAuth 1.0 身份验证的 Upwork API 请求 JSONP 文件?

html - 如何在 CalendarExtender 中设置当前日期

javascript - 创建复杂的 SVG,无需中间字符串

javascript - 使用正则表达式的URL “starts with”?

javascript - Jquery Show/Hide 在显示或隐藏之前将元素向右移动

javascript - 使用 JavaScript 检查事件日期是否有效

javascript - 使用 Ajax 的 onclick 事件更新数据库