douhuanqiao5290
douhuanqiao5290
2015-10-27 12:42
浏览 113
已采纳

Laravel 5.1 - 关于Ajax导航的刷新页面

In my app i have configured my navigation with ajax, so i can get my view's content (so only pure HTML) very quickly. I've also implemented javascript's history, so i can modify url on navigation.

But when i refresh the page on a url like my-app-/news, of course i get the same content asked by ajax: the view with only html, but in this case i need a complete view, not only the content.

route.php

Route::get('/', 'PagesController@index');
Route::get('/{page}', 'PagesController@ajaxCall');

PagesController.php

class PagesController extends Controller {

    public function index(){
        return view('pages.index');
    }

    public function ajaxCall($page){
        return view('content.'.$page)->render();
    }

}

How to create another route and method like my index where i can call the full view on page refresh?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douxiawei9318
    douxiawei9318 2015-10-27 13:04
    已采纳

    You can detect if the request was made via AJAX:

    class PagesController extends Controller {
    
        public function index(){
            return view('pages.index');
        }
    
        public function ajaxCall($page){
    
            if(\Request::ajax()) {
               return view('content.'.$page)->render();
            } else {
               return ... //complete view
            }
        }
    
    }
    
    点赞 评论
  • douzhi4056
    douzhi4056 2015-10-27 12:58

    It sounds very difficult.

    The term 'ajax' is very trivial. What do you use? jQuery, AngularJS?

    In your case, it's great to separate front-end and back-end. Use for example AngularJS (Single Page App!) that connects with your Laravel/Lumen back-end. Your back-end has to return json results only (RESTful controllers).

    Read this documentation: http://laravel.com/docs/5.1/controllers#restful-resource-controllers

    Why? I notice that you've troubles because mixing front-end and back-end. With for example AngularJS, you make a single page app. With routing, you can (re)load specific parts of the 'page'. It's also very easy to connect to the Laravel/Lumen API en handle the json output in your SPA. Your back-end has no (html) views and doesn't do redirects.

    Nice example: https://scotch.io/tutorials/create-a-laravel-and-angular-single-page-comment-application

    点赞 评论

相关推荐