javascript - 将 PHP 变量传递给 Javascript

标签 javascript php jquery wordpress

我已经将自定义 Google map 脚本实现为 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>

关于javascript - 将 PHP 变量传递给 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27697270/

相关文章:

javascript - getJSON 错误 - 不确定我哪里出错了

javascript - 如何在没有/g的情况下替换JavaScript中字符串中的所有句点?

javascript - d3js 强制按钮允许/禁用拖动操作

javascript - 如何在移动 View 中删除wordpress右侧的空格

php - 在插件激活上创建页面时遇到问题

php - Woocommerce 获取产品

php - 使用 ssl 公钥/私钥的基于 Web 的登录?

javascript - 倾斜不会改变 javascript 函数

jQuery 拖动滚动禁用

javascript - Node.js:POST 未将数据发送到数据库