Yii2 Pjax无法正常工作,重新加载整个页面

时间:2015-06-16 18:33:50

标签: php yii2 pjax

当在操作中使用file_get_contents($url)并且使用Pjax加载该操作时,整个页面将重新加载。

In controllers/SiteController.php

public function actionAbout()
{
    $url = 'http://api.dar.fm/topsongs.php?q=Music&page_size=20';
    $xml = file_get_contents($url);

    Yii::$app->view->params['xmldata'] = $xml;
    return $this->render('about');
}

In layouts/main.php

<?php Pjax::begin(); ?>
   <a href="/yiidev/web/index.php?r=site/home">Home</a> 
   <a href="/yiidev/web/index.php?r=site/about">About</a>
   <a href="/yiidev/web/index.php?r=site/contact">Contact us</a>  
<?php Pjax::end(); ?>

对于Home和Contact链接,只更新了pjax begin()end()之间的区域,但是对于About链接,整个页面重新加载。

如果我从file_get_contents()移除actionAbout()来电,那么页面重新加载就不会发生。我认为问题与使用file_get_contents()

从外部网址获取内容有关

3 个答案:

答案 0 :(得分:3)

问题是由于ajax超时。 file_get_contents()需要更多时间来执行,因为它正在读取外部URL并发生超时。通过增加超时时间来解决该问题。

Pjax :: begin([&#39; timeout&#39; =&gt; 5000]);

参考 https://github.com/yiisoft/yii2/issues/8819

答案 1 :(得分:1)

除了之前的回答,我提出了我的变体来解决超时问题 - 覆盖Pjax类的版本(我在所有项目中都使用它)。 当您忘记在Pjax构造函数中添加超时时,这可能有助于防止出现这种情况。

/**
 * Custom Pjax with incremented timeout.
 * JS for Pjax updating:
 *  <code>
 *      $.pjax.defaults.timeout = false;             // For JS use case yor should manual override default timeout.
 *      $.pjax.reload({container: '#pjaxId'});
 *
 *      // OR
 *      $.pjax.reload('#pjaxId', {timeout : false});
 *
 *      // OR for gridview with search filters
 *      $('.grid-view').yiiGridView('applyFilter'); // Thats true only if you have search Filters
 *  </code>
 *
 * Note: In more cases ID of widget should be static, because widgetId is autoincremented and browser version of page may be not up-to-date.
 */
class Pjax extends \yii\widgets\Pjax
{
    /**
     * @var int Timeout {@link \yii\widgets\Pjax::$timeout}.
     *          For JS use case yor should manual override defaults (  $.pjax.defaults.timeout = false;  ).
     */
    public $timeout = 30000;
}

在此处查看更多详情: yii2 how to use pjax when hyperlink is not in pjax

答案 2 :(得分:0)

使用<?php Pjax::begin(['id' => 'grid', 'timeout' => 0]) ?>设置无限超时或使用<?php Pjax::begin(['id' => 'grid', 'timeout' => 5000]) ?>。这里的时间以毫秒为单位。如果查询花费的时间超过超时中定义的时间,则会触发页面重新加载。默认超时为1000毫秒。您可以在Pjax Class文件中进行验证。