在PHP中使用JS变量需要一个棘手的想法。希望以棘手的方式显示数组值。
<?php
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
?>
var varCounter = 0;
var varName = function() {
if (varCounter <= 2) {
varCounter++;
document.write("<?php echo $cars[varCounter]; ?>");
} else {
clearInterval(varName);
}
};发布于 2014-08-13 08:52:12
考虑以下情况,当PHP代码在服务器上运行时,所有数据都嵌入到JavaScript (HTML)中。因此,PHP从不“看到”JavaScript值,但是JS可以访问所有可能的PHP值。
这些值(再次嵌入到PHP生成的HTML中)是通过编码,编码在一个漂亮的包中提供的-- JSON是JS对象文本的“足够近”,这样就可以可靠地工作(没有JSON_UNESCAPED_UNICODE选项的json_encode也不受链接测试的影响)。
<?php
// Array values come from PHP
$cars = array("Volvo", "BMW", "Toyota");
?>
<script>
// Don't forget JSON_HEX_TAG when using this method!
var cars = <?php echo json_encode($cars, JSON_HEX_TAG); ?>;
// Equivalent to the following with the above data, but in Real Life
// the data might come from a dynamic source or also be used in PHP.
// var cars = ["Volvo", "BMW", "Toyota"];
// Now all the data is available to JavaScript, which can be treated as
// a normal JavaScript array.
var varCounter = 0;
var varName = function() {
if (varCounter < cars.length) {
// Do *not* use document.write after the document is closed
alert(cars[varCounter]);
varCounter++;
} else {
clearInterval(varName);
}
};
// etc.
</script>https://stackoverflow.com/questions/25281758
复制相似问题