jQuery: Refresh div after another jquery action?

☆樱花仙子☆ 提交于 2019-12-06 03:54:04

问题


How do I refresh element (div, class whatever) after another jquery action?

I have this action which is deleting a record from database and I need to refresh div which is fetching some other data from database as well...

Well here's code:

$(function() {
    $(".delete").click(function() {
        var commentContainer = $(this).parent();
        var id = $(this).attr("id");
        var string = 'id='+ id ;

        $.ajax({
           type: "POST",
           url: "delete.php",
           data: string,
           cache: false,
           success: function(){
               commentContainer.slideUp('slow', function() {$(this).remove();});
           }
         });

        return false;
    });
});

Thanks for all help! :)


回答1:


During an AJAX call you can use the success function to run commands after a successful call. You already have a function in your code so its a simple matter of updating that function. The second div that you will like to update can be loaded with AJAX too.

 $.ajax({
  //other options
  success:function(){
       commentContainer.slideUp('slow', function() {$(this).remove();});
       $('#otherdiv').load('urlofpagewith info.php');
  }

 });



回答2:


Simply expose the data parameter of the success callback and replace the contents of whichever element, in this example div id="someDiv":

$.ajax({
   type: "POST",
   url: "delete.php",
   data: string,
   cache: false,
   success: function(data){
    commentContainer.slideUp('slow', function() {$(this).remove();});
    $('#someDiv').html(data);
  }
 });

See ajax options for more information.

Also, for the love of god don't use type names as variable names, it's really scary and terrible practice, even though string is not a reserved word in Javascript (use data: str or data: dataString instead).




回答3:


Why don't you add a function that do the refreshing after the first ajax is success (assuming that you cannot combine to the two into one ajax requist which a much more efficient).


...
function doRefresh_ofAnotherDiv() {
   $.ajax({
      type: ...,
      url: ...,
      data: ...,
      cache: ...,
      success: function(){
         // updateAnotherDiv();
      }
   });
}
...
$.ajax({
   type: "POST",
   url: "delete.php",
   data: string,
   cache: false,
   success: function(){
      commentContainer.slideUp('slow', function() {$(this).remove();});
      doRefresh_ofAnotherDiv();
   }
});
...

Hope this helps.




回答4:


almost all jquery functions have the ability to use callback functions. these are called whenever the original action is finished executing. so this can be used with any function, not just ajax.



来源:https://stackoverflow.com/questions/1488162/jquery-refresh-div-after-another-jquery-action

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!