Backbone pushState and Laravel 4 - Routes won'

2019-08-06 03:14发布

问题:

I've got a very simple setup of laravel 4 with 1 controller for trips. Now another simple setup of Backbone with a Router and routes to regular routes like trips, trips/create. I want to use pushState: true to have nice URL but I can't seem to get it to work. When I try to reach the URLs it sends me to the page served by the server with my json data.

However, if I type: www.mysite.com/#trips I am "redirected" to www.mysite.com/trips and then my method for this specific route triggers.

Here's my Router:

App.Router = Backbone.Router.extend({
routes: {
    '': 'index',
    'trips':            'trips',
    'trips/create':     'newTrip',
    'trips/:id':        'showTrip'
},

index: function(){

},

trips: function(){
    console.log('All trips') ;
},

newTrip: function(){

    console.log('New trip') ;

},

showTrip: function(id){
    console.log('trips id:' + id) ;
}
});

回答1:

This is probably caused by the Backbone router not being able to match the URL to your Backbone routes. To debug, add this to your routes:

'*actions':                 'defaultAction'

Then in the router add:

defaultAction: function(path) {
    console.log('Route "' + path + '" not defined, redirecting to homepage!');
}

You will probably see that the path is different from anything in your routes. To fix this, you need to tell Backbone the root of your paths. You do this while activating pushstates.

Backbone.history.start({
    pushState: true,
    root: 'http://mydomain.com/myapplication/'
});

Hope this helps.