如何将变量和数据从PHP传递到JavaScript?

我在PHP中有一个变量,我的JavaScript代码中需要它的值。如何将变量从PHP转换为JavaScript?

我有看起来像这样的代码:

<?php
     ...
     $val = $myService->getValue(); // Makes an API and database call
?>

我有需要val和看起来类似以下内容的JavaScript代码

<script>
    myPlugin.start($val); // I tried this, but it didn't work
    <?php myPlugin.start($val); ?> // This didn't work either
    myPlugin.start(<?=$val?> // This works sometimes, but sometimes it fails
</script>
逆天小卤蛋Green2020/03/11 17:34:21
<?php

    $val = $myService->getValue(); // Makes an API and database call

    echo "
        <script>
            myPlugin.start({$val});
        </script> ";

?>
飞云伽罗伽罗2020/03/11 17:34:21
  1. 将数据转换为JSON
  2. 调用AJAX接收JSON文件
  3. JSON转换Javascript对象

例:

步骤1

<?php

   $servername = "localhost";
   $username = "";
   $password = "";
   $dbname = "";
   $conn = new mysqli($servername, $username, $password, $dbname);

   if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
   } 

   $sql = "SELECT id, name, image FROM phone";
   $result = $conn->query($sql);

   while($row = $result->fetch_assoc()){ 
      $v[] = $row;    
   }

  echo json_encode($v);

  $conn->close();
?>

第2步

function showUser(fnc) {
   var xhttp = new XMLHttpRequest();

   xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
         // STEP 3    
         var p = JSON.parse(this.responseText);
      }
   }
}
D坤2020/03/11 17:34:21

我提出了一种使用PHP分配JavaScript变量的简单方法。

它使用HTML5数据属性存储PHP变量,然后在页面加载时将其分配给JavaScript。

完整的教程可以在这里找到

例:

<?php
    $variable_1 = "QNimate";
    $variable_2 = "QScutter";
?>
    <span id="storage" data-variable-one="<?php echo $variable_1; ?>" data-variable-two="<?php echo $variable_2; ?>"></span>
<?php

这是JavaScript代码

var variable_1 = undefined;
var variable_2 = undefined;

window.onload = function(){
    variable_1 = document.getElementById("storage").getAttribute("data-variable-one");
    variable_2 = document.getElementById("storage").getAttribute("data-variable-two");
}
飞云伽罗伽罗2020/03/11 17:34:21

尝试这个:

<?php
    echo "<script> var x = " . json_encode($phpVariable) . "</script>";
?>

-

-尝试了一段时间后

虽然可以,但是会降低性能。因为PHP是服务器端脚本,而JavaScript是用户端。

2020/03/11 17:34:21
<script>
  var jsvar = <?php echo json_encode($PHPVar); ?>;
</script>

json_encode()要求:

  • PHP 5.2.0或更高
  • $PHPVar 编码为UTF-8,Unicode。