这里有两个函数。
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/