jQuery:在另一个jquery动作之后刷新div?

如何在另一个jquery操作之后刷新元素(div,类什么)?

我有这个动作是从数据库中删除一条记录,我需要刷新div,这也是从数据库中获取一些其他数据…

那么这里的代码:

$(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; }); }); 

谢谢大家的帮助! 🙂

在AJAX调用期间,您可以使用success函数在成功调用后运行命令。 您已经在代码中使用了一个函数,因此更新该函数非常简单。 您想要更新的第二个div也可以加载AJAX。

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

只需公开成功回调的data参数并替换其中任何元素的内容,在本例中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); } }); 

有关更多信息,请参阅ajax选项 。

此外,对于上帝的爱,不要使用类型名称作为变量名称,它实际上是可怕和可怕的做法,即使string不是Javascript中的保留字 (使用data: strdata: dataString代替)。

为什么不添加一个在第一个ajax成功后进行刷新的函数(假设你不能将二者组合成一个更高效的ajax requist)。

 ... 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(); } }); ... 

希望这可以帮助。

几乎所有jquery函数都能够使用回调函数。 只要原始动作完成执行,就会调用它们。 所以这可以用于任何function,而不仅仅是ajax。