jquery点击发生得太快,无法刷新数据库的结果?

jquery点击发生得太快,无法刷新数据库的结果?

问题描述:

I'm making a simple shoutbox and when someone posts a message the message is added to the database just fine. I made a refresh button which populates all the messages in the text area. I am trying to call the .click() on the refresh button after the person enters the message but I think it happens too fast and doesn't catch the new message in the database. I works if I add an alert to give it more time. Is there a better way?

$("#shoutBtn").click(function(event){
   event.preventDefault();
   $.post("includes/shoutBoxPost.php", {"message": $("#messageBox").val(),
                                     "name": $("#userNameWelcome").html()});
   $("#messageBox").val("");
   $("#shoutRefresh").click();  
});

I changed my code to the long hand ajax way and it works thanks for answers folks

    $.ajax({
      type: 'POST',
      data: {"message": $("#messageBox").val(),
            "name": $("#userNameWelcome").html()},
      url : 'includes/shoutBoxPost.php',
      success : function(data) {
          $("#messageBox").val("");
          $("#shoutRefresh").click();
      }
    });

我正在创建一个简单的shoutbox,当有人发布消息时,消息会被添加到数据库中。 我制作了一个刷新按钮,用于填充文本区域中的所有消息。 我试图在人员输入消息后调用刷新按钮上的.click(),但我认为它发生得太快而且没有捕获数据库中的新消息。 如果我添加警报以便给它更多时间,我会工作。 有更好的方法吗? p>

  $(“#shoutBtn”)。click(function(event){
 event.preventDefault(); 
 $ .post(“  includes / shoutBoxPost.php“,{”message“:$(”#messageBox“)。val(),
”name“:$(”#userNameWelcome“)。html()}); 
 $(”#  messageBox“)。val(”“); 
 $(”#shoutRefresh“)。click(); 
}); 
  code>  pre> 
 
 

我改变了我的代码 对于长手ajax的方式,它的工作感谢答案人 p>

  $ .ajax({
 type:'POST',
 data:{“message”:$  (“#messageBox”)。val(),
“name”:$(“#userNameWelcome”)。html()},
 url:'includes / shoutBoxPost.php',
 success:function(data)  {
 $(“#messageBox”)。val(“”); 
 $(“#shoutRefresh”)。click(); 
} 
}); 
  code>  pre> \  n  div>

See the documentation for jQuery .post. You can define a success callback that will only fire once the post request successfully returns.

jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

$.post("includes/shoutBoxPost.php", 
    {"message": $("#messageBox").val(), "name": $("#userNameWelcome").html()},
    function( data, textStatus, jqXHR ) {
        $("#shoutRefresh").click();
    }
);

You need to wait for your post to finish and send a success message back (via JSON), then do the refresh action.

you can add call back function to your post

$.post( "includes/shoutBoxPost.php",{"message": $("#messageBox").val(), "name": $("#userNameWelcome").html()})
.done(function( data ) {
$("#messageBox").val("");
$("#shoutRefresh").click();
  });