0

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

它是这样工作的:

   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>"; 
   }

它应该看起来是动态的,它可以工作,当用户单击添加时,它会将帖子添加到他的收藏夹并使用删除链接重新加载页面。

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

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

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

4

3 回答 3

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

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

     e.stopPropagation(); 
});

包括这会阻止您的页面重新加载整个页面

于 2012-09-24T19:35:06.600 回答
0

如果您希望它是动态的,则需要使用 AJAX。jQuery 有ajax 支持,这使得这非常容易。如果您不熟悉 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('点击', 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
}
于 2012-09-24T20:01:44.600 回答
0

如果您可以使用 JQuery,那么您有一些工具可以完成此操作。

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

同样的想法也适用于您添加的“删除”链接。

所以,一般...

<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>
于 2012-09-24T20:02:52.417 回答