【问题标题】:Php angularJS project not showing data in a simple html tablePhp angularJS项目未在简单的html表中显示数据
【发布时间】:2018-03-14 19:18:21
【问题描述】:

我是 Php 和 AngularJS 新手...我在这些链接上关注了 2 个有趣的教程:

https://www.roytuts.com/rest-api-crud-example-in-php-mysql/

https://www.roytuts.com/angularjs-php-rest-crud-example/

第一个运行顺利,第二个在html表中没有显示数据库数据,不知道为什么。

以下所有项目文件: 文件 db.php

<?php

class Db {

    private $host = "localhost";
    private $db_name = "crudtests";
    private $username = "root";
    private $password = "";
    public $conn;

    // get the database connection
    public function getConnection() {
        $this->conn = null;

        try {
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->exec("set names utf8");
        } catch (PDOException $exception) {
            echo "Database connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }

}

?>

文件department.php

<?php

/**
 * Description of Department
 *
 * @author
 */
class Department
{

    // database connection and table name
    private $conn;

    private $table_name = "department";

    // object properties
    public $id;

    public $name;

    // constructor with $db as database connection
    public function __construct($db)
    {
        $this->conn = $db;
    }

    // reads all departments
    function read()
    {
        // query to select all
        $query = "SELECT d.dept_id, d.dept_name
            FROM
                " . $this->table_name . " d
            ORDER BY
                d.dept_id";
        // prepare query statement
        $stmt = $this->conn->prepare($query);
        // execute query
        $stmt->execute();
        return $stmt;
    }

    // create department
    function create()
    {
        // query to insert record
        $query = "INSERT INTO
                " . $this->table_name . "
            SET
                dept_name=:name";

        // prepare query
        $stmt = $this->conn->prepare($query);

        // sanitize
        $this->name = htmlspecialchars(strip_tags($this->name));

        // bind values
        $stmt->bindParam(":name", $this->name);

        // execute query
        if ($stmt->execute()) {
            return true;
        } else {
            return false;
        }
    }

    // update the department
    function update()
    {
        // update query
        $query = "UPDATE
                " . $this->table_name . "
            SET
                dept_name = :name
            WHERE
                dept_id = :id";

        // prepare query statement
        $stmt = $this->conn->prepare($query);

        // sanitize
        $this->name = htmlspecialchars(strip_tags($this->name));
        $this->id = htmlspecialchars(strip_tags($this->id));

        // bind new values
        $stmt->bindParam(':name', $this->name);
        $stmt->bindParam(':id', $this->id);

        // execute the query
        if ($stmt->execute()) {
            return true;
        } else {
            return false;
        }
    }

    // delete the department
    function delete() {
        // delete query
        $query = "DELETE FROM " . $this->table_name . " WHERE dept_id = ?";

        // prepare query
        $stmt = $this->conn->prepare($query);

        // sanitize
        $this->id = htmlspecialchars(strip_tags($this->id));

        // bind id of record to delete
        $stmt->bindParam(1, $this->id);

        // execute query
        if ($stmt->execute()) {
            return true;
        }

        return false;
    }
}

?>

文件读取.php

<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// include database and object files
require_once '../../config/db.php';
require_once 'Department.php';

// instantiate database and department object
$database = new Db();
$db = $database->getConnection();

// initialize object
$department = new Department($db);

// query department
$stmt = $department->read();
$num = $stmt->rowCount();

// check if more than 0 record found
if ($num > 0) {
    // department array
    $department_arr = array();
    $department_arr["records"] = array();

    // retrieve table contents
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        // extract row
        extract($row);
        $department_item = array(
            "id" => $row['dept_id'],
            "name" => $row['dept_name']
        );
        array_push($department_arr["records"], $department_item);
    }
    echo json_encode($department_arr);
} else {

   echo json_encode(array(
        "message" => "No products found."
    ));
}
?>

文件 app.js

/**
 * New module creation
 */

'use strict';

var app = angular.module('myCrudApp', []);

文件departmentController.js

/**
 *  Controller to handle user’s request/response
 */

'use strict';

angular.module('myCrudApp').controller('DepartmentController', ['$scope', 'DepartmentService', function($scope, DepartmentService) {
    var self = this;
    self.department = { id: null, name:'' };
    self.departments = [];

    self.submit = submit;
    self.edit = edit;
    self.remove = remove;
    self.reset = reset;


    findAllDepartments();

    function findAllDepartments(){
        DepartmentService.findAllDepartments()
            .then(
            function(d) {
                self.departments = d;
            },
            function(errResponse){
                console.error('Error while fetching departments');
            }
        );
    }

    function createDepartment(department){
        DepartmentService.createDepartment(department)
            .then(
            findAllDepartments,
            function(errResponse){
                console.error('Error while creating department');
            }
        );
    }

    function updateDepartment(department){
        DepartmentService.updateDepartment(department)
            .then(
            findAllDepartments,
            function(errResponse){
                console.error('Error while updating department');
            }
        );
    }

    function deleteDepartment(id){
        DepartmentService.deleteDepartment(id)
            .then(
            findAllDepartments,
            function(errResponse){
                console.error('Error while deleting department');
            }
        );
    }

    function submit() {
        if(self.department.id===null){
            console.log('Saving New Department', self.department);
            createDepartment(self.department);
        }else{
            updateDepartment(self.department);
            console.log('Department updated with id ', self.department.id);
        }
        reset();
    }

    function edit(id){
        console.log('id to be edited', id);
        for(var i = 0; i < self.departments.length; i++){
            if(self.departments[i].id === id) {
                self.department = angular.copy(self.departments[i]);
                break;
            }
        }
    }

    function remove(id){
        console.log('id to be deleted', id);
        if(self.department.id === id) {//clean form if the department to be deleted is shown there.
            reset();
        }
        deleteDepartment(id);
    }


    function reset(){
        self.department={id:null, name:''};
        $scope.myForm.$setPristine(); //reset Form
    }

}]);

文件departmentServices.php

/**
 * AngularJS service to communicate with Server
 */

'use strict';

angular.module('myCrudApp').factory('DepartmentService', ['$http', '$q', function($http, $q){

    var REST_SERVICE_URI = 'http://localhost/workspace/crudRestEsempio2/';

    var factory = {
        findAllDepartments: findAllDepartments,
        createDepartment: createDepartment,
        updateDepartment: updateDepartment,
        deleteDepartment: deleteDepartment
    };

    return factory;

    function findAllDepartments() {
        var deferred = $q.defer();
        $http.get(REST_SERVICE_URI+'restObjects/department/read.php')
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while fetching departments');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }

    function createDepartment(department) {
        var deferred = $q.defer();
        $http.post(REST_SERVICE_URI+'restObjects/department/create.php', department)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while creating department');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }


    function updateDepartment(department) {
        var deferred = $q.defer();
        $http.put(REST_SERVICE_URI+'restObjects/department/update.php', department)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while updating department');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }

    function deleteDepartment(id) {
        var deferred = $q.defer();
        $http.delete(REST_SERVICE_URI+'restObjects/department/delete.php?id='+id)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while deleting department');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }

}]);

有没有人有耐心帮我找出问题所在?

我使用了一些console.log()函数进行调试,“read.php”页面完美返回了JSON数据。

我没有报告 create.php、update.php 和 delete.php 文件,因为它们并不重要。 (仅供参考,html 页面使用“添加”按钮成功在数据库中创建了新记录,所以这不是数据库连接问题)。

【问题讨论】:

  • 您仍应在此处发布您的代码/教程代码。不鼓励外部链接,因为它们会中断,有些人不喜欢访问未知网站。
  • 如果你注释掉return factory;会发生什么?
  • 评论“返厂”;声明我在表格中仍然没有任何内容,并且按钮“编辑”和“删除”消失了。 “添加”按钮具有以下标签: {{!ctrl.department.id ? “添加”:“更新”}} 而不是“添加”。没有别的

标签: php html mysql angularjs


【解决方案1】:

问题解决了。

在read.php中创建JSON对象时,

echo json_encode($department_arr);

需要

echo json_encode($department_arr["records"]);

如果不这样做,则 JSON 对象是以错误的格式创建的,并且 Angular 绑定不起作用。

现在完美运行。

【讨论】:

    猜你喜欢
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多