1. 程式人生 > >關於pjax的一些坑

關於pjax的一些坑

靜態頁面中應用pjax看不到效果

由於我是在laravel中應用的pjax,所以在layouts中的app.blade.php中引用了pjax和nprogress的相關js和css。

建立公共程式碼pjax.blade.php

@extends('layouts.app')

@section('content')
<div class="container" id="pjax-container">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div
class="panel panel-default"> <div class="panel-heading">Test Pjax</div> <div class="panel-body"> <a data-pjax href="/pjax">origin</a><br> <a data-pjax href="/pjax1">pjax1</a><br> <a
data-pjax href="/pjax2">pjax2</a> </div> <div class="panel-heading">Pjax Page</div> @yield('pjaxCenter') </div> </div> </div> </div> @endsection

測試程式碼:
pjax.blade.php

@extends('layouts.pjax')
@section('pjaxCenter') <div class="panel-body"> I'm origin page </div> @endsection

pjax1.blade.php

@extends('layouts.pjax')

@section('pjaxCenter')
<div class="panel-body">
    I'm pjax1 page
</div>
@endsection

pjax2.blade.php

@extends('layouts.pjax')

@section('pjaxCenter')
<div class="panel-body">
    I'm pjax2 page
</div>
@endsection

建立pjax檔案:
pjax.js

$(function () {
    if ($.support.pjax) {
        $('#pjax-container').pjax('a[data-pjax]', '#pjax-container', {fragment: ('#pjax-container'), timeout: 8000});

        $(document).on('pjax:start', function () {
            NProgress.start();
        });
        $(document).on('pjax:end', function () {
            NProgress.done();
        });
    }
});

因為我這裡沒有動態的從php中分配資料,所以這裡如果我不加fragment引數的話,是不會啟用pjax的。pjax-container代表使用pjax區域性重新整理的範圍。如果你的pjax不生效的話可以試圖加上這個引數試一下哦。

通過pjax跳轉後,在跳轉後的頁面有些js不生效

有時候通過pjax跳轉之後的頁面會發現有些js都不生效了。
例如:

我在一個列表頁中點選一個文章,通過pjax跳轉到這篇文章的詳情頁。但這個詳情頁中引用了其他的js外掛,比如我引用的PDFObject外掛,還有uploader外掛,這時候會發現,當我跳轉到這個頁面的時候,這兩個外掛都不生效了,但當我在這個頁面重新重新整理時又生效了,在這裡看到了一個根本解決辦法。也發現了另一個比較方便的解決辦法。、

解決方案:將你的js放在pjax的container div標籤內。
pjax.js

$(function () {
    if ($.support.pjax) {
        $('#wrapper').pjax('a[data-pjax]', '#page-wrapper', {fragment: ('#page-wrapper'), timeout: 8000});

        $(document).on('pjax:start', function () {
            NProgress.start();
        });
        $(document).on('pjax:end', function () {
            NProgress.done();
        });
    }
});

app.blade.php

<div id="page-wrapper">
        @yield('content')
        <!-- JavaScripts -->
        <script src="{{ elixir('js/public.js') }}"></script>
        <script src="{{ elixir('js/app.js') }}"></script>
        <script src="{{ elixir('js/admin.js') }}"></script>
        <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    </div>

所以,我只將這些js放進了page-wrapper標籤內,重新試一下是否有用吧。