【问题标题】:For loop in json objectsjson对象中的for循环
【发布时间】:2018-09-09 01:03:03
【问题描述】:

我想在下面的 json 数据中循环。 console.log 可以工作,但不能在 javascript 函数中工作。 我希望 for for 循环在 javascript 函数中工作。 我希望 javascript 函数中的结果像

<script>
(function() {
      var questions = [ {
      question: "What is the value of 2 * 4";
      choices :[4, 8, 99, 11];
      correctAnswer: 1;},
{
      question: "What is the value of 2 * 8";
      choices :[4, 8, 16, 11];
      correctAnswer: 2;},

      ];

</script>

但是在控制台中出现错误。 控制台错误“预期的表达式,得到关键字'for'”这些是我的代码

<?php
$json_codes = array();


$sql = "SELECT  id, instructions,  quiz_question, correct, wrong, wrong1, wrong2  FROM student_quiz WHERE  subject ='SOCIAL STUDIES' AND type = 'challenge' ";
$results = $pdo->query($sql);
$results->setFetchMode(PDO::FETCH_ASSOC);
while($row = $results->fetch()) {
    $json_array['instructions'] = $row['instructions'];
    $json_array['quiz_question'] = $row['quiz_question'];
    $json_array['correct'] = $row['correct'];
    $json_array['wrong'] = $row['wrong'];
    $json_array['wrong1'] = $row['wrong1'];
    $json_array['wrong2'] = $row['wrong2'];
    array_push($json_codes,$json_array);
}

echo json_encode($json_codes);

?>
<script>
         var obj = <?php echo json_encode($json_codes);?>;

(function() {
  var questions = [ 

  for(a=0; a<obj.length; a++){
         document.write(obj[a]);

         }

  ];

【问题讨论】:

  • 你需要说出你期望它做什么以及它正在做什么。

标签: javascript php mysql json


【解决方案1】:

您确实尝试在数组的定义范围内表达循环。这是语法错误。

我建议使用for ( var something in obj )for ( var something of obj ) 而不是使用增量驱动的for-loops。根据您想要执行的操作,这可能首先会影响循环性能,并且至少那些 for-loop 比 for ( ... in ... )for ( ... of ... ) 更难阅读(和维护)。

您应该了解 JavaScript 语法的工作原理。数组的定义仅限于关联,您不能将处理指令(如循环)放在数组定义中(扩展运算符除外)。当使用循环将更多数据迁移到数组/对象时,您必须在定义之后运行它们。

至少,您应该考虑不要将定义放在 (function() { ... })(); 指令之外,这些指令可能不受 use strict-directives 或该指令遵循的惰性执行模型和范围排除的影响。

【讨论】:

    【解决方案2】:

    这是将数据从 PHP 端获取到 JavaScript 端的快速基本方法。检查 hte cmets - 我稍微更改了您的查询

    <?php
    $json_codes = array();
    
    // note slight change in query
    $sql = "SELECT instructions, quiz_question, correct, wrong, wrong1, wrong2  FROM student_quiz WHERE  subject ='SOCIAL STUDIES' AND type = 'challenge' ";
    $results = $pdo->query($sql);
    $results->setFetchMode(PDO::FETCH_ASSOC);
    
    while($row = $results->fetch()) {
        // the only var you weren't using from the select
        // was the primary key/id, 
        $json_codes[] = $row;
    }
    
    // we now have an indexed array of associative arrays
    // each of which represents a row from the db
    // and we make a json string out of the array
    $json_string=json_encode($json_codes);
    
    ?>
    
    <script>
        var data=JSON.parse('<?php print($json_string);  ?>');
        alert(data[0].quiz_question);
    </script>
    

    现在您可以通过 JavaScript 从 PHP 访问数据,我会考虑使用 Angular 等扩展 JS 引擎之一做一些事情。

    <?php
    $json_codes = array();
    
    // note slight change in query
    $sql = "SELECT instructions, quiz_question, correct, wrong, wrong1, wrong2  FROM student_quiz WHERE  subject ='SOCIAL STUDIES' AND type = 'challenge' ";
    $results = $pdo->query($sql);
    $results->setFetchMode(PDO::FETCH_ASSOC);
    
    while($row = $results->fetch()) {
        // the only var you weren't using from the select
        // was the primary key/id, 
        $json_codes[] = $row;
    }
    
    // we now have an indexed array of associative arrays
    // each of which represents a row from the db
    // and we make a json string out of the array
    $json_string=json_encode($json_codes);
    
    ?>
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title></title>
            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
            <script>
                var app = angular.module('myApp', []);
                app.controller('myCtrl', function ($scope) {
                    $scope.data = JSON.parse('<?php print($json_string); ?>');
                });
            </script>
        </head>
        <body>
            <div ng-app="myApp" ng-controller="myCtrl">
                <ul>
                    <li ng-repeat="datum in data">
                        {{datum.text}}    
                    </li>
                </ul>
                <ul>
                    <li ng-repeat="datum in data">
                        <ul>
                            <li ng-repeat="prop in datum">
                                {{prop}}
                            </li> 
                        </ul>
                    </li>
                </ul>
            </div>
        </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      • 2019-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多