如何用PHP变量填充JavaScript变量?
我必须使用PHP变量(来自DB)来填充JavaScript变量,如下所示:如何用PHP变量填充JavaScript变量?,javascript,php,variables,Javascript,Php,Variables,我必须使用PHP变量(来自DB)来填充JavaScript变量,如下所示: var oMain = new CMain({ mon: 100, min_: 10, max_: 25, time_bet: 0, time_winner: 500, win_occurrence: 65, cash:100000, fullscreen:true, check_orientation:true,
var oMain = new CMain({
mon: 100,
min_: 10,
max_: 25,
time_bet: 0,
time_winner: 500,
win_occurrence: 65,
cash:100000,
fullscreen:true,
check_orientation:true,
show_credits:true,
num_before_ads:1
});
我试图用JavaScript直接回显我的PHP变量(例如,mon:,
),但这不起作用
您有什么建议?您应该用引号将php代码括起来,因为此php语句
将返回字符串,并且要让js可读,它应该用引号括起来
mon:“”代码>
编辑:如果您正在打印数字,则应该对其进行解析,例如:
mon:parseInt(“”,10)代码>
mon:parseFloat(“”)代码>最佳实践是使用一个小型API,通过ajax调用并通过JSON检索值
<?php
$result = array(
'mon' => $mon,
'min_'=> $min,
'max_'=> $max,
'time_bet'=> $time_bet,
'time_winner'=> $time_winner,
'win_occurrence'=> $win_ocurr,
'cash'=>$cash,
'fullscreen'=>$fullscreen,
'check_orientation'=>$orientation,
'show_credits'=>$credits,
'num_before_ads'=>$num_before_ads
);
echo json_encode($result);
?>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
//manipulate your result
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "ajax_file.php", true);
xmlhttp.send();
</script>
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=函数(){
if(xmlhttp.readyState==XMLHttpRequest.DONE){
if(xmlhttp.status==200){
//操纵你的结果
}
else if(xmlhttp.status==400){
警报(“出现错误400”);
}
否则{
警报(“返回了200以外的内容”);
}
}
};
open(“GET”,“ajax_file.php”,true);
xmlhttp.send();
如果php已经加载并具有前端,则将其放入隐藏的输入或数据属性中。JS内部的混乱PHP回音很难看,也是一种糟糕的做法。您是否尝试过varmon=“”
mon:“”,
mon:parseInt(“”,10)
您的javascript是在php文档中还是在单独的js文件中?您还应该更详细地描述“但这不起作用”的含义。PHP错误?控制台中的JS错误?电脑着火了?没有新信息?那么,我们就有点困在这里了……如果值不是字符串,javascript就不需要引号。为什么要这样解析数字?如果$mon
包含有效的整数或浮点,则可以直接打印它,无需任何引号或解析。目前,我们甚至不知道OP是否试图在PHP文件中回显变量…@MagnusEriksson解析它更安全,有时你不能保证PHP变量有一个有效的整数或浮点值。那么我建议用PHP来做:echo(int)$mon
或echo(float)$mon
最佳实践表明,在获取数据时应该使用GET。