简体   繁体   English

CakePHP:创建我自己的函数

[英]CakePHP: creating my own functions

I have an Article controller & model. 我有一个Article控制器和模型。 I want to have a function that adds one to an integer when a link is clicked. 我希望有一个函数,当单击链接时,该函数会将一个整数加1。 So I have say a "i like" button (link) it takes me to Articles/thumbsup it will then take the thumbsup field of that article and increment it by one, then save the article, and redirect to the view. 因此,我说了一个“我喜欢”按钮(链接),它将带我到Articles / thumbsup,它将使用该文章的thumbsup字段并将其递增1,然后保存该文章并重定向到视图。

I'm not sure how to modify records in this way. 我不确定如何以这种方式修改记录。 I need to load the article, modify the data and then save it. 我需要加载文章,修改数据然后保存。

My hope is that this be handled by javascript so noone will see the url change. 我希望这可以由javascript处理,因此没人会看到url的变化。

Can someone help me out here? 有人可以帮我吗?

Thanks, 谢谢,

Jonesy 琼斯

Thanks, 谢谢,

Billy 比利

You can do that with an AjaxRequest. 您可以使用AjaxRequest做到这一点。

models/article.php: models / article.php:

function thumbsup($id = null)
  {
  $conditions = array('Article.id' => $id);
  $this->updateAll(
    array('Article.thumbsup' => 'Article.thumbsup + 1'),
    $conditions
    );
  $article = $this->find(
    'first',
    array('conditions' => $conditions, 'fields' => array('Article.thumbsup'))
    );
  return $article['Article']['thumbsup'];
  }

controllers/articles_controller.php: controllers / articles_controller.php:

function thumbsup($id = null)
  {
  $this->set('count', $this->Article->thumbsup($id));
  $this->layout = 'ajax';
  }

views/articles/thumbsup.ctp: 视图/文章/thumbsup.ctp:

<?php echo $count; ?>

webroot/js/thumbsup.js: webroot / js / thumbsup.js:

$(document).ready(function()
  {
  $('.iLikeSomething').click(function()
    {
    $.post('http://yoursite.com/articles/incrementThumbsup/'+this.id, function(data)
      {
      $('#iLikeSomethingCount').html(data);
      });
    });
  });

Html sample for clicking: 单击的HTML样本:

<span class="iLikeSomething" id="insertYourArticleIdHere" style="cursor: pointer;">iLike</span>
<div id="iLikeSomethingCount">0</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM