javascript - 将数组从 php 传递到 js

标签 javascript php json file

我的文件扩展名为 php.ini。在这里我从数据库中读取了信息。我需要将此数据(关联数组)传递给 js,该数据也包含在这个 php 文件中。

<?php
    require('../db.php');

    function var_dump1($arr) {
        echo '<pre>';
        var_dump($arr);
        echo '</pre>';
    }

    // load data from Database
    $query = R::getAll("SELECT * from questions");
    var_dump1($query);

?>

<script>
const arr = JSON.parse( '<?php echo json_encode($query); ?>' );
console.log(arr);

</script>   

输出:

var_dump1($query);

array(5) {
  [0]=>
  array(7) {
    ["id"]=>
    string(1) "1"
    ["question"]=>
    string(143) "The ______________ of a table is used to modify the design of a table, like modifying the name of a field or changing the data type of a field."
    ["answer1"]=>
    string(14) "Datasheet View"
    ["answer2"]=>
    string(11) "Desisn View"
    ["answer3"]=>
    string(10) "Table View"
    ["answer4"]=>
    string(11) "Wizard View"
    ["true_answer"]=>
    string(1) "1"
  }
  [1]=>
  array(7) {
    ["id"]=>
    string(1) "2"
    ["question"]=>
    string(83) "You can select multiple fields of a table in design view by using the ________ key."
    ["answer1"]=>
    string(3) "Alt"
    ["answer2"]=>
    string(8) "Spacebar"
    ["answer3"]=>
    string(5) "Shift"
    ["answer4"]=>
    string(4) "Ctrl"
    ["true_answer"]=>
    string(1) "3"
  }
...

console.log(arr);

Uncaught SyntaxError: missing ) after argument list

结论: 就php而言一切都很好。但是当我们尝试在 js 部分的 js 对象中解析这个数组时 - 我们看到奇怪的错误。

问题:

  1. 如何从 php 加载数据(例如,在我的例子中关联数组)到 js。当php和js在同一个扩展文件(php)中时。
    1. 如何从 php 加载数据(例如,在我的例子中关联数组)到 js。当php和js在不同的文件中时。例如,我们有 1 个扩展文件 php,我们在其中实现了逻辑(在我的例子中使用 DB)。我们需要将这些数据导入到扩展文件js中。

最佳答案

1)您需要做的就是:

<script>
var arr = <?php echo json_encode($query);?>; // <-- no quotes, no parsify
console.log(arr);
</script>

JSON = JavaScript 对象表示法...它已经采用了分配给 JavaScript 中使用的变量的格式。

虽然将它分配给“const”......可能不是一个好主意,因为它是一个对象,但这正是我阅读它们的方式,并且仍然完全可以:More Info .

2) 如果您从 js (ala ajax) 调用 php 文件,那么您可以从 php 返回中返回原始 JSON,具体取决于您如何进行 ajax 调用(以及使用什么库,例如 jquery)。 ..您可能需要也可能不需要执行JSON.parse(returnData)。没有足够的信息提供您想要如何做到这一点,无法给出可靠的答案。

关于javascript - 将数组从 php 传递到 js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49846127/

相关文章:

javascript - 如何更有效地做到这一点?

javascript - "sort not a function"仅在谷歌浏览器中出现 angularjs 错误

javascript - AWS Cognito 身份 NotAuthorizedException

php - 此 PHP 代码中未显示 Bangla 字体

PHP 转义字符

java - 如何将两个 json 元素转换为第一个元素的名称和第二个元素的值

javascript - 在 JavaScript/NodeJS 中压缩十六进制字符串

javascript - 如何在 Sublime Text3 中调试 PHP、Javascript 代码?

javascript - 从 geojson 获取最大值和最小值

json - 使用 Powershell 将 JSON 文件加载到 SQL Server 表中