使用PHP连接mysql和Knockout

时间:2017-04-12 14:24:12

标签: javascript php mysql rest knockout.js

我正在尝试使用PHP作为REST API和Knockout JS连接MySQL数据库以在UI中显示数据库。我能够建立从数据库到PHP的连接并查询数据。作为淘汰新手,我不确定如何使用Knockout正确显示数据。请在下面找到我的代码。感谢您的帮助。

PHP代码:

<?php
  $servername = "localhost";
  $username = "root";
  $password = "";
  $dbname = "employeedb";

  $conn = new mysqli($servername, $username, $password, $dbname);

  $sql = "SELECT `id`, `firstname`, `lastname`, `currentAddress`, `permanentAddress` FROM `employeedata` WHERE 1";

  $result = $conn->query($sql);
  $records = array();

  while($row = $result->fetch_array()) {
      $records[] = array(
          'id' => $row['id'], 'firstname' => $row['firstname'], 'lastname' => $row['lastname'], 'currentAddress' => $row['currentAddress'], 'permanentAddress' => $row['permanentAddress']
      );
  }

  echo json_encode($records);
?>

JS代码:

var dataModel = function  () {
    var self = this;

    this.employeeRecord = ko.observableArray([]);
    // Display Records
    this.displayRecord = function () {
        $.ajax({
            type : 'GET',
            datatype: "json",
            url: "js/phpapi.php",
            success: function (data) {
                var id = data['id'];
                var firstname = data['firstname'];
                var lastname = data['lastname'];
                var currentAddress = data['currentAddress'];
                var permanentAddress = data['permanentAddress'];
                self.employeeRecord.push(data);
            }
        });
    };
    this.displayRecord();
    console.log (self.employeeRecord());
};
ko.applyBindings(new dataModel());

我能够'GET''URL'正确,但整个数据显示在数组[0]中。如果我错过了什么,请告诉我。

输出:当console.log(数据)

"[{"id":"1","firstname":"Test Data","lastname":"number 1","currentAddress":"Temporary Current Address 1","permanentAddress":"Permanent Address 1"},
  {"id":"2","firstname":"Test Data","lastname":"number 2","currentAddress":"Temporary Current Address 2","permanentAddress":"Permanent Address 2"}]"

0 个答案:

没有答案