是否有一个CakePHP组件/插件,为ajax页面做永久链接

Is there a CakePHP component/plugin that does permanent links for ajax pages?

本文关键字:链接 ajax CakePHP 有一个 组件 插件 是否      更新时间:2023-09-26

我使用JsHelper编写JS链接以使用ajax加载页面。这样的:

<?= $this->Js->link($item['Series']['title'], array(
    'controller' => 'series',
    'action' => 'view',
    $item['Series']['id']
), array('update' => '#menu-items')); ?>

这是工作良好,但现在我想添加它,以便您可以链接到这些页面。例如,当你点击链接时,它会将你重定向到example.com/#!/series/2。然后,您也可以转到这个url,正确的页面将在#menu-itemsdiv中加载。

这是我必须从头开始写的东西,或者有一个CakePHP助手或插件可用,可以为我做吗?我以前有过这样做的经验,但从来没有使用过CakePHP,也不知道从哪里开始。

谢谢,

我现在已经尝试过自己解决这个问题,因为我认为没有响应,那么像这样的东西还没有为CakePHP构建。

首先,javascript:

var hash = '';
window.setInterval(function() {
    if(hash != location.hash) {
        hash = location.hash;
        if(hash.indexOf('#!/') != -1) {
            var url = hash.substr(2);
            $('#my-div').load(url);
        }
    }
}, 300);

检查location.hash是否发生了变化,如果发生了,则检查是否从#!/开始。(即#!/:controller/:action/:id是我正在寻找的哈希值)。然后调用jQuery的load函数来加载控制器和动作。

然后我必须修改我的链接,在HtmlHelper中使用url方法。

<?
$hashUrl = $this->Html->url(array(
    'controller' => 'categories',
    'action' => 'view',
    $category['Category']['id']
));
echo $this->Html->link($category['Category']['title'], '#!' . $hashUrl);
?>

这将为控制器和操作创建一个字符串,然后将其附加到link方法中的#!。这样做,可能看起来相当冗长(您可能可以编写一个自定义助手使其成为一行),但它允许您稍后更改config/routes.php中的url。最终得到这样一个url: #!/categories/view/2

最后,你需要确保在你的控制器中,你使用的每个方法的末尾都有这个。

$this->render('view', 'ajax');

我不认为这是一个完美的解决方案,但它目前做得很好。

有一些开源项目可以帮助您。下面是一个很好的起点:https://github.com/browserstate/history.js