繁体   English   中英

将数组从php传递到js

[英]Passing an array from php to js

我的文件扩展名为php。 在这里,我从数据库中读取了信息。 而且我需要将此数据(关联数组)传递给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 Object Notation ...,其格式已经可以分配给要在JavaScript中使用的变量。

尽管将其分配给'const'可能不是一个好主意,因为它是一个对象,但它只是我的阅读方式,而且还可以: 更多信息

2)如果您是从js(ala ajax)调用php文件,则可以从php返回中返回原始JSON,并根据您进行ajax调用的方式(以及使用的库,例如jquery)...您可能需要或不需要做JSON.parse(returnData) 没有足够的信息提供您想要如何做的可靠答案。

您应该了解JSON 它是可以用任何语言(包括JS)解析的语法。

只需使用PHP将数组响应到JacaScript代码即可,如下所示:

<script>
var myData = <?php echo json_encode($array);?>;
console.log(myData);
</script>

通常,您的php代码将呈现为html页面。 在此页面中,您可以根据需要构建数据。 示例(在您的php-代码中):

// as a js - variable: 
<script type="text/javascript">
<?php
var questions = <?php echo json_encode($query);
?>
alert(questions); // Output whatever is in the questions-variable
</script>

问题将是一个全局js变量,您可以从另一个js.file或嵌入在html文件中的js进行访问。

// As data in your html: 
<input type="hidden" id="id_questions" name="questions" 
value="<?php echo htmlspecialchars(json_encode($query)); ?>"
/>
// Then fetch this data using js-code, eg in a different js-file: 
alert(document.getElementById('id_questions').value());

也可以从外部js文件或嵌入在php代码的html输出中的js来实现。

暂无
暂无

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

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