php - 从 PHP 传递时未定义 Javascript 值

标签 php javascript undefined

更新:感谢所有提供帮助的人。我希望这里的无数解决方案可以为面临类似困难的任何人提供引用。

我正在使用 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);

如果有一种方法可以在外部 javascript 文件中从 PHP 中提取变量,我更愿意这样做。

最佳答案

从 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>

那么您就不必担心范围界定问题了?

关于php - 从 PHP 传递时未定义 Javascript 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7871684/

相关文章:

javascript - 为什么我定义的字符串打印到控制台时显示为未定义?

php - Joomla 插件 : "Another plugin is already using the named folder"

php - 如何在opencart中检查属于特定产品的属性

php - wp_remote_get 和 url 参数

javascript - 可观察或观察者中的错误处理?

javascript - 无法访问Javascript变量: undefined

php - 使用 $_POST 将选定的项目值发送到服务器

D3 中的 Javascript 模块模式

javascript - javascript日期构造函数中的日期溢出

c# - WCF 服务在 JavaScript 中返回 "is undefined"