2016-04-13 47 views
0

我使用Cakephp 2.8.0。我的問題是ajax。我不知道如何在我的應用程序中實現ajax。我有李鏈接的類別,並點擊後,我需要刪除一些HTML代碼,並在我的控制器中找到必要的類別,並得到這個數組在響應HTML和打印它。Galleryphp中加載ajax的圖片庫

我PhotosController行動:

public function getPhotoByCategory($category = null) 
{ 
    $category=$_GET['category']; 
    debug($category); 
    $this->render('getPhotoByCategory', 'ajax'); 
} 

我的HTML代碼:

<div class="lol"> 
      <ul> 
       <?php foreach($categories as $category):?> 
       <li> 
        <a href="<?php echo $category['Category']['cat_name'];?>" class="lol"><?php echo $category['Category']['cat_name'];?></a> 
       </li> 
       <?php endforeach;?> 
      </ul> 
     </div> 

我的JS代碼:

$(".lol").click(function (e) { 
    e.preventDefault(); 
    var category = $(this).attr("href"); 
    $.ajax({ 
     type: 'get',category, 
     data: {catyegory: 
     url: '<?php echo $this->Html->url(array('controller' => 'Photos', 'action' => 'getPhotoByCategory')); ?>', 
     success: function(response) { 
      if (response.error) { 
       alert(response.error); 
       console.log(response.error); 
      } 
      if (response.content) { 
       $('#target').html(response.content); 
      } 
     }, 
     error: function(e) { 
      alert("An error occurred: " + e.responseText.message); 
      console.log(e); 
     } 
    }); 
}); 

請幫我在CakePHP中右AJAX這種情況。

回答

0

我發現處理AJAX獲取項目的最佳方式是創建要插入項目的元素(在您的案例中來自類別的照片)。

PhotosController.php

public function getPhotoByCategory($category = null) 
{ 

    $this->set('photos', $this->Photo->find('all', ['conditions' => ['category_id' => $category]]); 
    $this->render('Elements/getPhotoByCategory'); 
} 

在上面例子中的元素包含一個for循環,通過$照片循環並輸出。這是然後裝入使用下面這JS代碼格 「笑」:

查看/圖片/ get_photo_by_category.ctp

<button class="loadphoto">Load Photos</button> 
<div class="lol"> 
</div> 

JS代碼(視圖頂部?)

$('.loadphotos').click(function(e) { 
    $('.lol').load('/Photos/getPhotoByCategory/1') 
    .fail(alert("error")); 
}); 

Dereuromark已經做了一些不錯的文檔AJAX and CakePHP