简体   繁体   English

从php发送数组到javascript文件

[英]send an array from php to javascript file

I want to send an array that is being created on a php file to a javascript file. 我想将在php文件上创建的数组发送到javascript文件。 The codes that I have made are the below but I cannot make it work. 我编写的代码如下,但我无法使其正常工作。

sample.php sample.php

<form action="new-game.php" method="post">
<?php $playerNames = array();
    for ($i=0; $i<$_POST["playerNo"]; $i++) {
        echo "<form name=\"input\" action=\"#\" method=\"POST\">Όνομα: <input type=\"text\" name=\"playerName\" value=\"\"><br/>";
        $playerNames[$i] = $_REQUEST['playerName'];
    }
?>

    </br></br>
    <input type="submit" value="Αποστολή" onclick='showNames(<?php echo json_encode($playerNames); ?>);' />
</form>

And I don't know how I should use the $playerNames array on script.js file. 而且我不知道如何在script.js文件中使用$ playerNames数组。

Have you included your javascript file ? 您是否包含了javascript文件? And is the function showNames() present ? 函数showNames()是否存在?

<script type="text/javascript" src="yourfile.js"></script>

Look at my example to send datas from PHP to Javascript. 看我的示例,将数据从PHP发送到Javascript。 The trick is to close the PHP tag, and to open a Javascript one. 诀窍是关闭PHP标记,然后打开一个Javascript。

<?php
    $my_array; //replace by your own array
    for($i = 0; $i < count($my_array) -1; $i++) {
    ?>
        <script>
            myFunction(<?php echo $my_array[$i]; ?> );
        </script>
    <?php   
} 
?>

EDIT : 编辑:

It seems to me that this line is wrong. 在我看来,这条线是错误的。

<input type="submit" value="Αποστολή" onclick='showNames(<?php echo json_encode($playerNames); ?>);' />

Try using this following one instead : 尝试使用以下替代方法:

<input type="submit" value="Αποστολή" onclick='showNames(<?php echo json_encode($playerNames); ?>)' />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM