我有一个变量在PHP,我需要它的值在我的JavaScript代码。我怎么能把我的变量从PHP到JavaScript?
我有这样的代码:
<?php
$val = $myService->getValue(); // Makes an API and database call
在同一页上,我有JavaScript代码,需要$val变量的值作为参数传递:
<script>
myPlugin.start($val); // I tried this, but it didn't work
<?php myPlugin.start($val); ?> // This didn't work either
myPlugin.start(<?=$val?>); // This works sometimes, but sometimes it fails
</script>
这是在2022年对我有用的,我使用这个解决方案来获取当前用户的电子邮件
我使用PHP创建了一个短代码,并将其添加到PHP .function:
function my_get_current_user_email(){
$current_user = wp_get_current_user();
$email = $current_user->user_email;
return $email;
}
add_shortcode( 'get_email', 'my_get_current_user_email');
然后使用div来包装短代码:
<div id="target-content" style="display: none;">
[get_email]
</div>
最后,使用JavaScript访问Div的内容:
const databox = document.getElementById("target-content");
const dataContent = databox.textContent;
console.log(dataContent)
这工作完美地为我想要的,我希望它也会为你工作。
我想出了一个简单的方法来分配JavaScript变量使用PHP。
它使用HTML5数据属性来存储PHP变量,然后在页面加载时分配给JavaScript。
例子:
<?php
$variable_1 = "QNimate";
$variable_2 = "QScutter";
?>
<span id="storage" data-variable-one="<?php echo $variable_1; ?>" data-variable-two="<?php echo $variable_2; ?>"></span>
<?php
下面是JavaScript代码
var variable_1 = undefined;
var variable_2 = undefined;
window.onload = function(){
variable_1 = document.getElementById("storage").getAttribute("data-variable-one");
variable_2 = document.getElementById("storage").getAttribute("data-variable-two");
}