gpt4 book ai didi

Yii2:如何为脚本使用 Asset Bundle

转载 作者:行者123 更新时间:2023-12-05 00:42:20 25 4
gpt4 key购买 nike

我已经阅读了文档,但不知道该怎么做,例如我在 View 文件夹 medicine-issue-entry< 中的文件 index.php 中有一个小脚本 像:

<?php
$js = 'function refresh() {
$.pjax.reload({container:"#medicine_request_entry"});
setTimeout(refresh, 60000); // restart the function every 5 seconds
}
refresh();';
$this->registerJs($js, $this::POS_READY);
?>

我可以在哪里将这段代码放在一个单独的文件中,以及如何将它包含在相关文件中。一个详细的过程将不胜感激。谢谢。

好的,我正在使用基本模板。在 AppAsset.php 中,我包含了类似内容

public $js = [

'js/autorefresh.js'
];

并在 web 文件夹 中创建了一个文件夹 js 并使用以下代码创建了一个新文件 autorefresh.js:

function refresh() {
$.pjax.reload({container:"#medicine_request_entry"});
setTimeout(refresh, 60000); // restart the function every 5 seconds
}
refresh();

在我的 index.php 中添加了这一行

namespace app\assets;
use app\assets\AppAsset;
AppAsset::register($this);

但是还是不行,我是不是还漏掉了什么?当我使用 registerJs 将代码包含在文件中时,它工作正常。

注意:查看页面源文件时,文件已正确发布并单击链接显示脚本,但代码无法正常工作。

最佳答案

使用 Yii2 的基本模板

将您的autorefresh.js 脚本添加到/web/js/ 目录

function refresh() {
$.pjax.reload({container:"#medicine_request_entry"});
setTimeout(refresh, 60000); // restart the function every 5 seconds
}
refresh();

将您的脚本添加到位于 /assets/AppAsset.php 的 AppAsset 类内的 $js 数组中

<?php
namespace app\assets;
use yii\web\AssetBundle;

class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
'js/autorefresh.js',
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}

确保您的 AssetBundle 已注册。

use app\assets\AppAsset;
AppAsset::register($this);

\app\assets\AppAsset::register($this);

NOTE: Your don't set the namespace of the index.php file.

关于Yii2:如何为脚本使用 Asset Bundle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28075019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com