我想用 Symfony 1.4 在 Ajax 中创建一个“喜欢/不喜欢”按钮。
我有这些表:
| Song | ------- n --------------------------- n ---------- | sfGuardUser |
|
| LikeSong | `
我已经阅读了 symfony AJAX 文档,但它是 1.0 文档。1.4很轻。所以,这是我首先尝试做的。
在/app/frontend/module/likesong/_voting.php
:
<?php
if($song->hasVote())
{
jq_link_to_remote('I do not like', array('complete' => '[??? Update my link]', 'url' => 'likesong/notlike?id_song='.$song->getId()));
}
else
{
jq_link_to_remote('I like', array('complete' => '[??? Update my link]', 'url' => 'likesong/like?id_song='.$song->getId()));
}
echo ' - '.$song->getNbVote();
?>
在/app/frontend/config/routing.yml
:
song_like:
url: /song-like/:id
param: { module: song, action: like }
song_notlike:
url: /song-not-like/:id
param: { module: song, action: notLike }
在/app/frontend/module/likesong/actions.class.php
public function executeLike(sfWebRequest $request)
{
if ($request->isXmlHttpRequest())
{
if(USER HAS NOT YET VOTED)
{
$this->vote = new LikeSong();
$this->vote->setSongId($this->song()->getId());
$this->vote->setSfGuardUserId($this->getUser()->getId());
$this->vote->save();
return $this->renderText('notlike');
else
{
// Display flash
}
}
}
public function executeNotLike(sfWebRequest $request)
{
if ($request->isXmlHttpRequest())
{
if(USER ALREADY VOTED)
{
// Delete form database
return $this->renderText('like');
else
{
// Display flash
}
}
}
当用户点击时,“我喜欢这首歌”应该替换为“我不喜欢这首歌”。