【问题标题】:Gallery load with ajax in cakephp在 cakephp 中使用 ajax 加载图库
【发布时间】:2016-04-13 12:01:15
【问题描述】:

我使用的是 Cakephp 2.8.0。我的问题是ajax。我不知道如何在我的应用程序中实现 ajax。我有带有类别的 li 链接,单击后我需要删除一些 html 代码并在我的控制器中找到必要的类别并在响应 html 中获取此数组并打印它。

我的 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 来解决这种情况。

【问题讨论】:

    标签: javascript php jquery ajax cakephp


    【解决方案1】:

    我发现处理 AJAX 以获取项目的最佳方法是创建您要插入的项目的元素(在您的情况下,照片来自一个类别)。

    PhotosController.php

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

    上面示例中的元素包含一个 for 循环,该循环遍历 $photos 并输出它们。然后使用下面的 JS 代码将其加载到 div "lol" 中:

    视图/照片/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 上做了一些不错的文档

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多