Hongmu Notes
Home Language Notes How to pass variables to js files in php? (How does the code in the js file obtain external variables?)
Language Notes PHP JavaScript

How to pass variables to js files in php? (How does the code in the js file obtain external variables?)

How to pass variables to js files in php? (How does the code in the js file obtain external variables?)

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.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 140
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 187
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 231

Recommended reading

Visual Brand Innovation Design Website Template 0044

Visual Brand Innovation Design Website Template 0044 Practical Collection Yiyou template

This EyouCMS template is designed for a visually-driven brand innovation website, featuring a creative and stylish design approach that effectively showcases brand design works, innovative case studies, and design concepts. It enables brand design agencies to demonstrate their professional expertise online and attract corporate clients. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS (...
👁 49
Construction Machinery (Bulldozers & Excavators) Website Template – 0669

Construction Machinery (Bulldozers & Excavators) Website Template – 0669 Practical Collection Yiyou template

This EyouCMS template is ideal for the construction machinery, bulldozer, and excavator industries. Its professional yellow design style is perfect for showcasing bulldozer and excavator products, construction machinery equipment, technical specifications, and construction case studies. It helps construction machinery companies showcase their products online and attract clients in the infrastructure and mining sectors. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: EyouCMS Installation Guide...
👁 26
(PC + WAP) pbootCMS Marketing-Driven Outdoor亭式亭子 Website Template – Download Blue Outdoor Billboard Website Source Code (0011)

(PC + WAP) pbootCMS Marketing-Driven Outdoor亭式亭子 Website Template – Download Blue Outdoor Billboard Website Source Code (0011) Practical Collection pbootcms Template

This is a PbootCMS website template designed for marketing-oriented outdoor security booth and billboard businesses, featuring a cyan-themed design and compatibility with both desktop and mobile devices. The template is geared towards driving marketing conversions; through clear product categorization, case study displays, and online engagement guidance, it can effectively help outdoor facility manufacturers or advertising agencies enhance their customer acquisition capabilities – making it an ideal choice for creating a professional marketing-oriented corporate website. Template Display | Installation Instructions | Website Backend: /admin.php | Username:...
👁 45
(Adaptive mobile version) PBootCMS template for industry association and trade union websites; Download source code for institutional and organizational websites – 0617

(Adaptive mobile version) PBootCMS template for industry association and trade union websites; Download source code for institutional and organizational websites – 0617 Practical Collection pbootcms Template

A PbootCMS website template designed for industry associations, trade unions, and government agencies, supporting both PC and WAP devices. Its professional and sophisticated design makes it ideal for organizations such as industry associations, chambers of commerce, and trade unions to showcase their functions and activities. This template helps public institutions establish an official online information dissemination platform. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn (Related...)
👁 68
Visual Website Design Company – Website Template 0045

Visual Website Design Company – Website Template 0045 Practical Collection Yiyou template

An EyouCMS website template designed specifically for visual website and web design agencies. It features a modern, creative design style ideal for showcasing website design projects, digital marketing case studies, and service offerings. This template helps web design agencies attract business clients looking to build their own websites online. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 70
Responsive Heavy-Duty Equipment Accessories Website Template 0670

Responsive Heavy-Duty Equipment Accessories Website Template 0670 Practical Collection Yiyou template

An EyouCMS responsive website template designed for the heavy-duty equipment and accessories industry. Its professional industrial design style is ideal for showcasing heavy-duty equipment products, accessory ranges, technical specifications, and industrial applications. This template helps heavy-duty equipment manufacturers showcase their products online and attract industrial customers. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS...
👁 38