pjax没有使用laravel

时间:2013-10-12 13:32:10

标签: jquery laravel pjax

我正在尝试设置pjax,但它不起作用。每当我点击pjax链接时,网址都会更改为domain.com/foo(没有更改html内容),然后更改为domain.com/#,然后正常重定向到domain.com/foo。为什么呢?

这是我触发pjax的方式: $(document).pjax('a[data-pjax]', '#wrapper');

在我的控制器中我有这个:

public function getIndex() {
    $posts = $this->loginOptions();

    $this->layout->title = 'My title';      
    $content = View::make('foo.bar')
        ->with('title', $this->layout->title)
        ->with('posts', []);

    if (Request::header('X-PJAX'))
        return $content;
    else 
        $this->layout->content = $content;
}

我的HTML(我点击链接的第一页)如下所示:

<DOCTYPE html>
<head></head>
<html>
    <body>
    <div id='wrapper'>
        <a data-pjax href='foo'>Foobar</a>
    </div>
    <script src='http://code.jquery.com/jquery-2.0.0.min.js'></script>
    <script src='jquery.pjax.js'></script>
    <script src='script.js'></script>
    </body>
</html>

如果我使用X-PJAX标头运行标准的ajax调用,我会得到正确的html(这意味着我的If正在工作),但是url没有改变,这就是我想使用pjax的原因。

$.ajax({
    url: '/login',
    type: 'get',
    beforeSend: function(xhr){ 
        xhr.setRequestHeader('X-PJAX', true); 
        xhr.setRequestHeader('X-PJAX-Container', '#wrapper') 
    },
    success: function(resp) { $('#wrapper').html(resp); }
})

3 个答案:

答案 0 :(得分:3)

你是如此亲密:D

JS:

$(document).pjax('a[data-pjax]', '#wrapper', { fragment: '#wrapper});

由于pjax正常工作,因此更改了#并因此导致重新加载,但找不到具有id #wrapper的HTML元素,因此它会运行到超时并重新加载页面。这种行为是必要的,因为较旧的浏览器(没有pushstate / popstate / ajax支持)然后加载所有链接,如页面是静态的。

尝试更改此内容:

 if (Request::header('X-PJAX'))
        echo '<div id="wrapper"> pjaxxx </div>';
    else 
        $this->layout->content = $content;

我知道你已经使用history.js解决了这个问题,但是pjax解决了愚蠢的hashbanging并且一旦实现就很容易使用。

希望你还读这个,欢呼!

答案 1 :(得分:1)

我放弃了pjax。我现在正在使用history.js

使用Javascript:

History.Adapter.bind(window,'statechange',function(){
    var State = History.getState();
    $.ajax({
        url: State.url,
        type: 'get',
        beforeSend: function(xhr){ 
            xhr.setRequestHeader('X-PJAX', true); 
        },
        success: function(resp, status, xhr) { 
            document.title = xhr.getResponseHeader('Page-Title');
            $('#wrapper').html(resp); 
        }
    });
});

$(document).on('click', 'a[data-pjax]', function(e){
    e.preventDefault();

    var self = $(this);

    History.pushState(null, 'Loading page...', self.attr('href'));
});

PHP(控制器):

public function getIndex() {
    $this->layout->title = 'My Title';      
    $content = View::make('my.view')
        ->with('title', $this->layout->title)
        ->with('posts', []);

    if (Request::header('X-PJAX')) {
        return Response::make($content)
            ->header('Page-Title', $this->layout->title);
    } else 
        $this->layout->content = $content;
}

答案 2 :(得分:0)

我刚刚开始使用Rob Crowe的Turbo ......

https://github.com/rcrowe/Turbo

就像一个魅力

(在引擎盖下使用pjax)