JSON对象中的For循环

时间:2018-09-09 01:03:03

标签: javascript php mysql json

我想在for循环中获取以下json数据。 console.log正在运行,但无法在javascript函数中运行。 我希望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>

但是在控制台中出现错误。 控制台错误“期望的表达式,关键字为””,这是我的代码

<?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]);

         }

  ];

2 个答案:

答案 0 :(得分:0)

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

我建议使用#<Bootsnap::LoadPathCache::Store::NestedTransactionError: Bootsnap::LoadPathCache::Store::NestedTransactionError> /usr/local/var/rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/bootsnap- 1.3.1/lib/bootsnap/load_path_cache/store.rb:43:in `transaction' /usr/local/var/rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/bootsnap- 1.3.1/lib/bootsnap/load_path_cache/cache.rb:130:in `push_paths_locked' /usr/local/var/rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/bootsnap- 1.3.1/lib/bootsnap/load_path_cache/cache.rb:113:in `block in reinitialize' /usr/local/var/rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/bootsnap- 1.3.1/lib/bootsnap/load_path_cache/cache.rb:107:in `synchronize' /usr/local/var/rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/bootsnap- 1.3.1/lib/bootsnap/load_path_cache/cache.rb:107:in `reinitialize' /usr/local/var/rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/bootsnap- 1.3.1/lib/bootsnap/load_path_cache/cache.rb:46:in `find' /usr/local/var/rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/bootsnap- 1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:28:in `require' /usr/local/var/rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/ activesupport #<LoadError: cannot load such file -- rails/backtrace_cleaner> /usr/local/var/rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/bootsnap- 1.3.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require' for ( var something in obj )而不是使用增量驱动的for ( var something of obj )循环。根据您要执行的操作,这可能首先会对循环性能产生影响,至少那些for循环比for或{{1}更难读取(和维护) }。

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

至少,您应该考虑不要将定义放在for ( ... in ... )指令之外,这些指令可能不受for ( ... of ... )指令或该指令遵循的延迟执行模型和范围排除的影响。

答案 1 :(得分:0)

这是从PHP端到JavaScript端获取数据的快速基本方法。检查评论-我对您的查询做了些更改

<?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访问数据,我将考虑使用扩展的JS引擎(例如Angular等)来做些事情。

<?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>