2016-03-12 38 views
0

您好我有数组年在我的控制器:改变一个函数到第二按钮点击

public function getNextYear() { 

    $years = $this->getYears(); 
    foreach ($years as $key => $value) { 
     $y[] = $value + 1; 
    } 
    return $y; 
} 

我在指数显示此:

<?php foreach ($years as $year): ?> 

     <div class=""> 

      <?= $year; ?><br> 

     </div> 

    <?php endforeach; ?> 
<?php endif; ?><br> 

这是possibe至一年使用add只有PHP?

回答

1

没有。您将需要使用Ajax将更多内容加载到视图中。另外,你会检查是否有更多的年份加载,然后显示一个按钮,用Javascript/Jquery调用Ajax。这个请求会将内容直接放到你的页面中,手段,你的函数getNextYear()必须返回一个Json或Html内容。

如果结果是Json,则使用AJax回调,格式为HTML。

这一切后,与按钮一起,把一个div,一些阶级把更多的内容:

<button id="callAjaxNextYears"></button> 
<div class="nextYears"></div> 

不要忘了,在你的Ajax发送的最后一年表现。然后,你可以使用类似:

<button value="2012"></button> 

而在你的功能,必须认识到一个_GET或_POST或帕拉姆:

getNextYear($start){} 

由于更好的做法,几年这一切名单必须由ajax实现,以避免项目中的标准代码。或者,您可以了解更多关于“AngularJS”的信息。


试着改变你的PHP函数与Ajax调用更好的工作:

public $actualYear; 
public $maxYear = 2030; // Just a exemple, otherwhise, will create infinite years list 

public static function getYears() { 

     if(isset($this->actualYear)){ 
      $nowYear = $this->actualYear; 
     } else { 
      $nowYear = date("Y"); 
      $this->actualYear = 2010; 
     } 

     if($nowYear < $maxYear){ 

      $i = 0; 
      for ($yearNum = $this->actualYear; $yearNum <= $nowYear; $yearNum++) { 
       $year[] = $yearNum; 
       $i++; 
       if ($i == 3) 
        break; 
      } 

     } 

     return $year; 
    } 

public function getNextYear() { 

    $this->actualYear = $_POST['start']; // Wherever your ajax has sended, can be a _GET as well 

    $years = $this->getYears(); 
    foreach ($years as $key => $value) { 
     $y[] = $value + 1; 
    } 
    return $y; 
} 

如果选择不使用AJAX,试试这个:

<a href="?start=2012">Load more years</a> 

然后在控制器:

public $maxYear = 2030; // Just a exemple, otherwhise, will create infinite years list 

public static function getYears() { 

     if(isset($_GET['start'])){ 
      $nowYear = $_GET['start']; 
     } else { 
      $nowYear = date("Y"); 
      $this->actualYear = 2010; 
     } 

     if($nowYear < $maxYear){ 

      $i = 0; 
      for ($yearNum = $this->actualYear; $yearNum <= $nowYear; $yearNum++) { 
       $year[] = $yearNum; 
       $i++; 
       if ($i == 3) 
        break; 
      } 

     } 

     return $year; 
    } 
+0

你能告诉我更多细节吗?我的功能是什么$开始?我只想改变我的索引中的第一个foreach。在thi foreach我有$年后点击我想那里$ nextYear值 – qwerty

+0

已更新。试试这个 – Kezzbr

+0

但是改变我的按钮功能。我知道我的函数工作,我检查了这与var_dump我只想知道我能做些什么,使按钮做一些行动来重新加载页面,并显示我从第二功能 – qwerty

相关问题