最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Writing JSON array to html page with javascript after getting it from PHP query - Stack Overflow

programmeradmin1浏览0评论

I have a MySQL query that I pass to a PHP array. The PHP array is turned into a JSON array using json_encode. I am trying to then get this to print onto my html page. Here is what I have so far.

<?php
class db {
  public $conn;

  function dbLogin() {
    $this->conn = new mysqli("1.2.3.4","user","pwd","db");  
  }

  public function selectQuery() {
    $this->dbLogin();
    $query = "
        SELECT      *
        FROM        tekken_7_frame_data
    ";
    echo "<pre>";
    $resultArray = Array();
    if ($result = $this->conn->query($query)) {
        while ($row = $result->fetch_array()) {
            $resultArray[] = $row;
        }

    }

    echo "</pre>";
    $resultJson = json_encode($resultArray);
  }
}

$fData = new db();
$fData->selectQuery();
?>

<html>
<head>
</head>
<body>
<script>
  var jsonArray = <?php echo $resultJson ?>;
  document.write(jsonArray);
  for (i = 0; i < jsonArray.length; i++) {
    document.write(jsonArray[i][1]);
  }
</script>
</body>
</html>

I've read up on other similar questions on StackOverflow with no luck; my html page is pletely blank. I've tried placing json_econde(...) inside of the javascript variable jsonArray instead of in my PHP class. That didn't work either. I have also var_dump'd the PHP array with no issue (the whole thing displayed on the page), as well as placed the array in a PHP variable using json_encode, then echoed that array with no issue.

I have no idea how to access this JSON array. I ultimately want it in a table, but because this is my first time bridging the gap between PHP and Javascript, I figured that I would take it one step at a time so that I know exactly what is going on.

I have a MySQL query that I pass to a PHP array. The PHP array is turned into a JSON array using json_encode. I am trying to then get this to print onto my html page. Here is what I have so far.

<?php
class db {
  public $conn;

  function dbLogin() {
    $this->conn = new mysqli("1.2.3.4","user","pwd","db");  
  }

  public function selectQuery() {
    $this->dbLogin();
    $query = "
        SELECT      *
        FROM        tekken_7_frame_data
    ";
    echo "<pre>";
    $resultArray = Array();
    if ($result = $this->conn->query($query)) {
        while ($row = $result->fetch_array()) {
            $resultArray[] = $row;
        }

    }

    echo "</pre>";
    $resultJson = json_encode($resultArray);
  }
}

$fData = new db();
$fData->selectQuery();
?>

<html>
<head>
</head>
<body>
<script>
  var jsonArray = <?php echo $resultJson ?>;
  document.write(jsonArray);
  for (i = 0; i < jsonArray.length; i++) {
    document.write(jsonArray[i][1]);
  }
</script>
</body>
</html>

I've read up on other similar questions on StackOverflow with no luck; my html page is pletely blank. I've tried placing json_econde(...) inside of the javascript variable jsonArray instead of in my PHP class. That didn't work either. I have also var_dump'd the PHP array with no issue (the whole thing displayed on the page), as well as placed the array in a PHP variable using json_encode, then echoed that array with no issue.

I have no idea how to access this JSON array. I ultimately want it in a table, but because this is my first time bridging the gap between PHP and Javascript, I figured that I would take it one step at a time so that I know exactly what is going on.

Share Improve this question edited May 19, 2015 at 1:32 aCarella asked May 19, 2015 at 1:15 aCarellaaCarella 2,57814 gold badges58 silver badges92 bronze badges 9
  • Have you tried just echoing the php variable directly to isolate the problem? Ie is the problem the PHP, or the JS? Have you viewed the page source? Check the console to make sure JS is running happily? – Luke Commented May 19, 2015 at 1:17
  • Yea, I should have added that. I have var_dump'd the PHP array with no problem. I have placed the PHP array into a variable using json_encode, then printed that variable with no problem either. Both arrays display on the page in full. No errors in the console when I display both arrays either. – aCarella Commented May 19, 2015 at 1:19
  • Also, code is a bit odd. You should either return a value, or echo in the function. The problem may be that $resultJson variable that appears within the function, and then over in the JS part, also. I'd remend you edit your function to NOT echo a <pre>, and to return the array. And then you'll have something like $result = $db->selectQuery();, and then echo $result;. – Luke Commented May 19, 2015 at 1:20
  • 3 YOu have a typo in the for loop. It should be i < jsonArray.length, not i > jsonArray.length. This is causing the loop to end immediately without printing anything. – Barmar Commented May 19, 2015 at 1:21
  • 1 Haha Barmar may have spotted the problem. Also, critiquing the DB class: should have initial capital for the class name, the field should be private, and the connection should be established in the constructor rather than for every query you make :) And I think there's a fetch_all or similar method that returns the results as an array in the first place! – Luke Commented May 19, 2015 at 1:23
 |  Show 4 more ments

2 Answers 2

Reset to default 4

Try to change your function (don't use echo! but return something) to:

public function selectQuery() {
    $this->dbLogin();
    $query = "
        SELECT      *
        FROM        tekken_7_frame_data
    ";
    $resultArray = Array();
    if ($result = $this->conn->query($query)) {
        while ($row = $result->fetch_array()) {
            $resultArray[] = $row;
        }

    }

   return json_encode($resultArray);
  }

and downthere:

$fData = new db();
$resultJson = $fData->selectQuery();

The best way to get data from PHP into JavaScript is to use an asynchronous request (that is, "AJAX").

A javascript library greatly simplifies this process. Here's a rough example using AngularJS (http://angularjs).

json.php

// this file JUST needs to print JSON as string.
<?php
class db {
  public $conn;

  function dbLogin() {
    $this->conn = new mysqli("1.2.3.4","user","pwd","db");  
  }

  public function selectQuery() {
    $this->dbLogin();
    $query = "
        SELECT      *
        FROM        tekken_7_frame_data
    ";
    $resultArray = Array();
    if ($result = $this->conn->query($query)) {
        while ($row = $result->fetch_array()) {
            $resultArray[] = $row;
        }

    }    
    return json_encode($resultArray);
  }
}

$fData = new db();
print $fData->selectQuery();
?>

myscript.js

// this will fetch your JSON string from the PHP file and 
// set $scope.myData to a JS object.
// it sets $scope.myDataString to a JSON stringified format.

angular.module('myApp' [])
  .controller('myController', function($http, $scope) {
    var $scope.myData = {};
    var $scope.myDataString = '';
    function getMyData () {
      $http.get('/json.php')
      .success( function (data) {
        $scope.myData = data;
        $scope.myDataString = JSON.stringify(data);
      })
      .error(function (err) {
         $scope.myData = {error: err};
         $scope.myDataString = "ERROR: "+JSON.stringify(data);
      })
    }
    getMyData();
  }

mypage.html

<!-- include angular and your app's file. 
     make sure to link in your app and controller -->
<html>
<head>
    <script src="https://ajax.googleapis./ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script src='myscript.js'>
</head>
<body ng-app='myApp'>
  <main ng-controller='myController as myCtrl'>
    <div id='myOutput'>{{myDataString}}</div>
  </main>
</body>
</html>
发布评论

评论列表(0)

  1. 暂无评论