douyo770657 2017-06-08 20:26
浏览 32
已采纳

从php到javascript文件的数组

I have a php file that I gather data on an array and I need to send this data to an external javascript file. I have read that I need to encode data to JSON format and echo the variable stored, then I try to use this variable on the javascript file but I get an error "Can't find variable: jArray" What I do wrong?

file.php

<?php $playerNames_new = array();
for ($i=0; $i<$_POST["playerNo"]; $i++) {
    $j = $i+1;
    echo "<form name=\"input\" action=\"#\" method=\"POST\">Player Name $j: <input type=\"text\" name=\"playerName[]\" value=\"\"><br/>";
        $playerNames_new[$i] = $_REQUEST['playerName'];
}


?> 
<script type="text/javascript">var jArray = <?php echo json_encode($playerNames_new); ?>;</script>
<script type="text/javascript" src="script.js"></script>

script.js

$(document).ready(function() {
// global variables
var playerNames = jArray;});
  • 写回答

1条回答 默认 最新

  • douyan2821 2017-06-08 20:42
    关注

    The following works for me.

    <script> var php = <?php echo json_encode([1, 2 ,3]); ?>;</script>
    <script src="s.js"></script>
    

    or

    <script> var php = <?php echo json_encode([1, 2 ,3]); ?>;</script>
    <script> console.log(php); </script>
    

    the console log

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考