Is there a CakePHP component/plugin that does perm

2019-09-12 07:43发布

问题:

I'm using the JsHelper to write JS links to use ajax to load in a page. Like this:

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

This is working fine, but now I'd like to add it so that you can link to these pages. So, for example, when you click the link it would redirect you to example.com/#!/series/2. You could then also go to this url and the correct page would be loaded in the #menu-items div.

Is this something I'd have to write from scratch, or is there a CakePHP helper or plugin available that would do it for me? I have experience in doing something like this before, but never with CakePHP and unsure where to start.

Thanks,

回答1:

I've had a go at tackling it myself now, as I figured that as there was no response then something like this wasn't already built for CakePHP.

So first, the 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);

What this does is check to see if the location.hash has changed, if it has, then it checks to see if it starts with #!/. (I.e #!/:controller/:action/:id is the hash that I'm looking for). It then just calls the jQuery load function to load that controller and action.

I then had to modify my links to use the url method in the HtmlHelper.

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

echo $this->Html->link($category['Category']['title'], '#!' . $hashUrl);
?>

This creates a string for the controller and action, then appends it to #! in the link method. Doing it this way, may seem quite long winded (You could probably write a custom helper to make it one line) but it allows you to change the URLs in the config/routes.php later on. You end up with a url like this: #!/categories/view/2

Lastly, you need to make sure that in your controllers you have this at the end of each of method you use.

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

I'm not imagining that this is a perfect solution, but it does the job quite nicely at the moment. Open to suggestions for improvement too.



回答2:

There are open source projects that may be able to help you along. Here's a good starting point: https://github.com/browserstate/history.js