将 PHP 变量传递给 Javascript

Pass PHP variables to Javascript

本文关键字:Javascript PHP 变量      更新时间:2023-09-26

我已经实现了一个自定义的谷歌地图脚本作为WordPress简码,但我对.js文件中定义的一些值有问题,但由WordPress通过PHP生成

这是.js文件:

//set your google maps parameters
var latitude = 41.03328,
    longitude = 21.30281,
    map_zoom = 16;
//google map custom marker icon - .png fallback for IE11
var is_internetExplorer11= navigator.userAgent.toLowerCase().indexOf('trident') > -1;
var marker_url = ( is_internetExplorer11 ) ? 'img/cd-icon-location.png' : 'img/cd-icon-location.svg';
//define the basic color of your map, plus a value for saturation and brightness
var main_color = '#00e1ff',
    saturation_value= -20,
    brightness_value= 5;

我需要做的是在线获取图像的 Wordpress 主题目录:

'img/cd-icon-location.png' : 'img/cd-icon-location.svg'

对于var main_color = '#00e1ff',从 PHP 获取此值

<?php echo oneengine_option( 'main_color' ); ?>

我通常使用 PHP 获取 JS 值是在导入 JS 脚本或编写的代码之前声明它们

<?php
    echo '<script type="text/javascript">var main_color = "'.$main_color.'";</script>';
?>
<script type="text/javascript" src="someJSScript.js">
    //If not in separate file, JS code will go here
</script>

将您需要的 PHP 变量回显到主题文件中的 Javascript 变量中,并在脚本文件中引用 JS 变量。

主题文件:

<script>
    var config_theme_directory = "<?=get_template_directory()?>";
</script>

包含的 JS 文件:

console.log( config_theme_directory );