If you want to pass variables from PHP into a JavaScript file, you have a few options:
Inline JavaScript:
You can use PHP variables directly in JavaScript code in HTML files, just like you did in the example code. This allows PHP to include the values of PHP variables when generating JavaScript code. But this approach couples PHP code and JavaScript code together, which may not be clear and easy to maintain.
var videoMd5 = '<?= $videoMd5 ?>';Use global variables:
You can assign PHP variables to JavaScript global variables and use this global variable directly in JavaScript files. This method requires defining the global variable in the HTML file and ensuring that the JavaScript file is loaded before use.
In the HTML file:
<script>
var videoMd5 = '<?= $videoMd5 ?>';
</script>
<script src="/path/to/video_player.js"></script>In the JavaScript file:
document.addEventListener('DOMContentLoaded', function() {
var player = videojs('my-video');
// 使用全局变量 videoMd5
var progress = localStorage.getItem('video_progress_' + videoMd5);
if (progress) {
player.currentTime(progress);
}
player.on('timeupdate', function() {
localStorage.setItem('video_progress_' + videoMd5, player.currentTime());
});
});Passed via HTML attributes:
You can use custom attributes in HTML tags to pass the value of a PHP variable to JavaScript. For example, in <script> in tags data-* Set the value of the PHP variable in the property, and then pass it in the JavaScript file getAttribute() method to get this value.
In the HTML file:
<script src="/path/to/video_player.js" data-videomd5="<?= $videoMd5 ?>"></script>In the JavaScript file:
document.addEventListener('DOMContentLoaded', function() {
var player = videojs('my-video');
// 从 data-videomd5 属性获取 videoMd5 的值
var videoMd5 = document.currentScript.getAttribute('data-videomd5');
var progress = localStorage.getItem('video_progress_' + videoMd5);
if (progress) {
player.currentTime(progress);
}
player.on('timeupdate', function() {
localStorage.setItem('video_progress_' + videoMd5, player.currentTime());
});
});Each of these three methods has advantages and disadvantages, and you can choose the most suitable method according to your specific situation.