如何在不重新加载所有页面的情况下单击链接时刷新div内容?

时间:2012-09-24 19:32:17

标签: php jquery mysql ajax html

在我的网站中,作者(用户)可以将帖子标记为收藏。

它的工作原理如下:

   if ($favinfo == NULL || $favinfo == "") { 
      $favicon = "<a href=\"".$siteurl."/author/favorites.php?add=".$articleinfo['id']."\">ADD</a>"; .
   }
    else { 
      $favicon = "<a href=\"".$siteurl."/author/favorites.php?remove=".$articleinfo['id']."\">REMOVE</a>"; 
   }

它看起来很动态,当用户点击ADD时,它会将帖子添加到他的收藏夹并使用REMOVE链接重新加载页面。

问题是它不是真正动态的,它会重新加载所有页面。

我怎样才能重新加载该链接(在div内)?

我知道我必须使用ajax,jquery等,但我尝试了一些在S.O.中找到的例子。但没有成功。

3 个答案:

答案 0 :(得分:1)

 $('a').on('click', function(e){

    // the default for a link is to post a page..    
    // So you can stop the propagation

     e.stopPropagation(); 
});

包含此停止页面重新加载整个页面

答案 1 :(得分:0)

如果您希望它是动态的,则需要使用AJAX。 jQuery有ajax support这使得这很容易。如果你不熟悉ajax或javascript,你应该先阅读它。

PHP

if ($favinfo == NULL || $favinfo == "") { 
    $favicon = "<a class=\"fav-btn\" data-id=\"".$articleinfo['id']."\" data-action=\"add\" href=\"".$siteurl."/author/favorites.php"\">ADD</a>"; .
}
else { 
    $favicon = "<a class=\"fav-btn\" data-id=\"".$articleinfo['id']."\" data-action=\"remove\" href=\"".$siteurl."/author/favorites.php"\">REMOVE</a>"; 
}

的JavaScript

  

$('a.fav-btn')。on('click',function(e){

  var $this = $(this),                    // equates to the clicked $('a.fav-btn')
      url = $this.attr('href'),           // get the url to submit via ajax
      id = $this.attr('data-id'),         // id of post
      action = $this.attr('data-action'); // action to take on server


  $.ajax({
      url: url+'?'+action+'='+id
  }).done(function(){ // once favorites.php?[action]= is done...

      // because this is in .done(), the button will update once the server has finished
      // if you want the link to change instantly and not wait for server, move this outside of the done function
      if(action === 'add'){
          $this.attr('data-action', 'remove').html('REMOVE'); // update the button/link
      }else{
          $this.attr('data-action', 'add').html('ADD');
      }

  })

  return false; // prevent link from working so the page doesn't reload
}

答案 2 :(得分:0)

如果您对使用JQuery感到满意,那么您可以使用一些工具来完成此任务。

  1. 拥有识别链接的结构/方法。
  2. 您可以在添加按钮上设置click()侦听器,该侦听器将调用JQuery $.post(url, callback)函数。
  3. 在该回调函数中,您可以使用“删除”链接更新相应的DIV(您在#1中定义的)。即如果您通过ID识别DIV,则可以通过$('#id')检索它,然后更新该对象。
  4. 您添加的“删除”链接也适用同样的想法。

    所以,通常......

    <button id="add">Add</button>
    
    <div id="links"> ...</div>
    
    <script>
    $('#add').click(function() { 
         $.post('your url',
             function(data) {
                 var links = $('#links');
                 // update your links with 'remove' button, etc
             }
         );
    });
    
    </script>