不能将PHP数组传递给Javascript

Can't pass PHP array to Javascript

本文关键字:Javascript 数组 PHP 不能      更新时间:2023-09-26

我有一个json_encoded的PHP数组,我想传递给Javascript:

$unmatched = json_encode(compareCourseNum($GLOBALS['parsed_courseDetails'], get_course_num_array($GLOBALS['bulletin_text'])));
$GLOBALS['unmatched'] = $unmatched;
print "<center><strong>Total number of courses parsed: $number_of_courses/" . "<span onClick='"show_array(<?php echo $unmatched; ?>);'">" . count_courses($GLOBALS['bulletin_text']) . "</span>" . "</strong></center>";

然而,当我运行脚本时,打印的内容是这样的:

Total number of courses parsed: 98/);">108

Javascript也不起作用。应该打印的是这样的:

Total number of courses parsed: 98/108

当我单击"108"时,Javascript应该可以通过显示数组元素的警报来工作。

我该如何解决这个问题?

这是Javascript:

function show_array (array) {
    //var array = <?php echo $unmatched; ?>;
    alert();
    var result = "",
        length = array.length;
    for (var i = 0; i < length; ++i) {
        result += array[i] + "'n";
    }
    alert(result);
}

更新:我删除了php标签和分号,所以现在是

"<span onClick="show_array( $unmatched);">"

但是show_array仍然没有运行!当我查看页面源代码时,我看到以下内容:

"<span onClick="show_array( ["220","221","242E","249B","250","254","255","256","256S","272A","285"]);">"

请帮忙?我知道这不是show_array代码的问题,而是数组输入的问题,因为当我传递像 [133, 234, 424] 这样的数字数组时,它有效,但不适用于字符串数组。

UPDATE2:

好的,我设法通过用单引号替换json_encoded数组中的双引号来使 Javascript 工作:

$unmatched = str_replace('"', '''', $unmatched);

但我不明白为什么我需要这样做。

您可以尝试使用 JSON_NUMERIC_CHECK 作为 json_encode() 中的第二个参数(需要 PHP>= 5.3.3)。

另一种选择是在 JavaScript 中使用 parseInt()

result += parseInt(array[i], 10);

...onClick='"show_array(<?php echo $unmatched; ?>);'">" . count_courses($GLOBALS['bulletin_text']) . "</span>" . "</strong></center>";

应该是

...onClick='show_array($unmatched);'>" . count_courses($GLOBALS['bulletin_text']) . "</span>" . "</strong></center>";

也就是说,删除打开的结束PHP标签和分号,您已经处于PHP解析模式。

下面的 html 有两个重要的部分。第一个显示最小的php,主要是文字标记。第二个有一个php包装器,围绕着第一个的整个内容。

为了简单起见,我用文字替换了一些代码。

<html>
  <head>
    <script>
      function show_array (array) {
        var result = "",
        length = array.length;
        for (var i = 0; i < length; ++i) {
          result += array[i] + "'n";
        }
        alert(result);
      }
    </script>
  </head>
  <body>
    <?php $unmatched = json_encode(array(1,2,3,4,5)); ?>
    <!-- Minimal php, only to pass the php array to JavaScript. -->
    <center><strong>
      Total number of courses parsed: 
      <span onClick="show_array(<?php echo $unmatched ?>)">
        15
      </span>
    </strong></center>
    <!-- Wrapper in php. 
         1. Wrap the previous markup in an echo.
         2. Escape the double quotes.
         3. Remove the php stuff around $unmatched.
         4. Profit.
    -->
    <?php echo "
    <center><strong>
      Total number of courses parsed: 
      <span onClick='"show_array( $unmatched )'">
        15
      </span>
    </strong></center>
    "; ?>
  </body>
</html>