更新:感谢所有帮助过我们的人。我希望这里的无数解决方案可以作为任何面临类似困难的人的参考。
我正在用PHP从一个文本文件中读取数据,我需要将字符串传递到JS中进行操作。我尝试了一种更直接的方法,将PHP放到外部JS文件中,但这不起作用,所以我求助于使用一个空的div容器。然而,在JS中,我仍然得到一个未定义的值。该文件正确读取div值,只是不会传递给我的外部javascript文件。
HTML:
<?php
$world = file_get_contents('http://url.com/testworld.txt');
//echo $world;
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="js/game.js"></script>
</head>
<body onload="init()">
<canvas id="game" width="650" height="366" style="border: 2px solid black;"></canvas>
<br />
<h1> Currently in development.</h1>
<br />
<div id="world" value="<?php echo $world; ?>" />
</body>
</html>和JS:
var world = document.getElementById('world').value;
document.write(world);如果有一种方法可以从PHP中提取外部javascript文件中的变量,我更愿意这样做。
发布于 2011-10-24 14:00:08
从PHP -> JS传递数据非常容易,而无需将其隐藏在DOM中。诀窍在于json_encode()函数-它会将php字符串、数组等转换成有效的javascript格式。请参见下面的示例,修复:
<?php
$world = file_get_contents('http://url.com/testworld.txt');
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="js/game.js"></script>
</head>
<body onload="init()">
<script type="text/javascript">
//World is defined here, and accessible to the javascript that runs on the page
var world = <?=json_encode($world)?>;
</script>
<canvas id="game" width="650" height="366" style="border: 2px solid black;"></canvas>
<br />
<h1> Currently in development.</h1>
<br />
</body>
我很确定你的麻烦是由于javascript中变量作用域的工作方式造成的。这个简单的示例必须适用于您:
<?php
$foo = "\"Hello world!\"";
?>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var foo = <?=json_encode($foo)?>;
alert("The value of foo is: " + foo);
</script>
</body>
</html>因此,在内联脚本的上下文中,存在foo变量。如果你的代码看起来像这样:
<script type="text/javascript">
//Load the game world, and pass to the javascript lib
var world = <?=json_encode($world)?>;
loadWorld(world);
</script>那你就不用那么担心作用域了?
发布于 2011-10-24 13:50:42
value对DOM元素有特殊的意义(它指的是文本框的值等)。相反,您可以使用data-value之类的HTML5 Data Attribute,然后使用document.getElementById('world').getAttribute('data-value');对其进行检查。
但是,更好的方法是使用隐藏输入,例如
<input type="hidden" id="world" value="<?php echo $world; ?>" />然后让你的脚本保持原样。
发布于 2011-10-24 14:00:42
另一种方式:在你的php中
<div id="world" data-world="<?php echo $world; ?>" />在你的JS中:
$('#world').attr('data-world');此外,您可能希望确保$world的值被正确转义,以便用作html属性
https://stackoverflow.com/questions/7871684
复制相似问题