Angularjs CRUD应用PUT方法不起作用

时间:2015-06-02 16:01:04

标签: php angularjs crud put slim

我正在使用php框架做一个angularjs CRUD应用程序Slim作为后端,这个应用程序差不多完成但我的PUT方法不起作用,我真的不明白为什么。

这是我的修身代码:



<?php
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();

// create new Slim instance
$app = new \Slim\Slim();
$app->get('/users', 'getUsers');
$app->post('/addUser', 'addUser');
$app->put('/edit/:id', 'updateUser');
$app->delete('/users/:id', 'deleteUser');
$app->run();
function getUsers() {
  $sql = "select * FROM name ORDER BY id";
  try {
    $db = getConnection();
    $stmt = $db->query($sql);  
    $wines = $stmt->fetchAll(PDO::FETCH_OBJ);
    $db = null;
    echo json_encode($wines);
  } catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}'; 
  }
}
function addUser() {
  $request = \Slim\Slim::getInstance()->request();
  $user = json_decode($request->getBody());
  $sql = "INSERT INTO name (name) VALUES (:name)";
  try {
    $db = getConnection();
    $stmt = $db->prepare($sql);  
    $stmt->bindParam("name", $user->name);
    $stmt->execute();
    $user->id = $db->lastInsertId();
    $db = null;
    echo json_encode($user); 
  } catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}'; 
  }
}

function updateUser($id) {
  $request = Slim::getInstance()->request();
  $body = $request->getBody();
  $user = json_decode($body);
  $sql = "UPDATE name SET name=:name WHERE id=:id";
  try {
    $db = getConnection();
    $stmt = $db->prepare($sql);  
    $stmt->bindParam("name", $user->name);
    $stmt->bindParam("id", $id);
    $stmt->execute();
    $db = null;
    echo json_encode($user); 
  } catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}'; 
  }
}

function deleteUser($id) {
  $sql = "DELETE FROM name WHERE id=:id";
  try {
    $db = getConnection();
    $stmt = $db->prepare($sql);  
    $stmt->bindParam("id", $id);
    $stmt->execute();
    $db = null;
  } catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}'; 
  }
}
function getConnection() {
  $dbhost="127.0.0.1";
  $dbuser="root";
  $dbpass="000000";
  $dbname="users";
  $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  
  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  return $dbh;
}

?>
&#13;
&#13;
&#13;

这是我的angularjs代码:

&#13;
&#13;
'use strict';

var app = angular.module('mainApp', ['ngRoute', 'ngResource']);


app.config(function($routeProvider) {
	$routeProvider
	.when('/', {
		controller: 'MainCtrl',
		templateUrl: 'views/users.html'
	})
	.when('/addUser', {
		controller: 'MainCtrl',
		templateUrl: 'views/add.html'
	})
	.when('/edit/:id', {
		controller: 'MainCtrl',
		templateUrl: 'views/edit.html'
	})
	.otherwise({
		redirectTo: '/'
	});
});


app.controller('MainCtrl', ['$scope', '$http', '$location', '$routeParams' , function($scope, $http, $location, $routeParams) {
  $scope.master = {};
  $scope.activePath = null;

  $http.get('api/users').success(function(data) {
    $scope.users = data;
  });

  $scope.deleteUser = function (user) { 
    console.log('service delete ' + user.id);
    $http.delete('api/users/' + user.id).success(function(){
      $location.path('/adminlist')
    });
  }

 $scope.addUser = function(user, AddNewForm) {
    console.log(user);
    $http.post('api/addUser', user).success(function(){
      $scope.reset();
      $scope.activePath = $location.path('/');
    });
    $scope.reset();
  };

  $scope.updateUser = function(user, AddNewForm) {
    console.log(user);
    $http.put('api/edit/' + $routeParams.id, {id:$routeParams.id, name:user.name}).success(function(){
      $scope.reset();
      $scope.activePath = $location.path('/');
    });
    $scope.reset();
  };

 $scope.reset = function() {
    $scope.user = angular.copy($scope.master);
  };
}]);
&#13;
&#13;
&#13;

最后我的HTML代码,这是一个显示所有用户的模板:

&#13;
&#13;
<!-- Show existing users. -->
<h2>Striped Rows</h2>
  <p>The .table-striped class adds zebra-stripes to a table:</p>       


  <table class="table table-striped">
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Delete</th>
        <th>Edit</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="user in users">
        <td>{{user.id}}</td>
        <td>
          {{user.name}}
      </td>
        <td><a ng-click="deleteUser( user )">delete</a></td>
        <td>( <a href="#/edit/{{user.id}}">edit</a> )</td>
      </tr>
    </tbody>
  </table>
<!-- Add a new friend to the list. -->
&#13;
&#13;
&#13;

当我想要更新用户时,这是我的页面:

&#13;
&#13;
<h2>Edit user</h2>
<form novalidate name="AddNewForm" id="add-new-form" method="post" action="">
  <label for="user">Name:</label>
  <input type="text" ng-model="user.name" required />
  <br/>
  <button class="btn btn-primary" ng-disabled="AddNewForm.$invalid || isUnchanged(user)" id="add-new-btn" ng-click="updateUser(user)">Edit!</button>
</form>
&#13;
&#13;
&#13; !

这很奇怪,因为当我按下编辑按钮时,我在这个表单中输入另一个名字,当我点击按钮时,我可以在网络中看到一切都有效,但似乎我在某个地方出了个错误,你可以在图片上看到它

enter image description here

也许有人可以链接我一些如何做到这一点的例子? 感谢您的关注:))

1 个答案:

答案 0 :(得分:2)

我尝试通过工厂进行所有API交互,而不是在每个控制器中编写方法来获取API数据。您只需调用方法并将参数传递给它。

// Rest API data factory
function ApiData($http)
{
    var query = '';
    var domain = 'mydomain.com/';

    return {
        get: function (endpoint, params) {
            return $http({
                method: 'GET'
                , url: domain + endpoint
                , params: params
            })
            .then(function (response) {
                return response.data;
            });
        },
        post: function (endpoint, params) {
            return $http({
                method: 'POST'
                , url: domain + endpoint
                , params: params
            })
            .then(function (response) {
                return response.data;
            });
        },
        put: function (endpoint, params) {
            return $http({
                method: 'PUT'
                , url: domain + endpoint
                , params: params
            })
            .then(function (response) {
                return response.data;
            });
    }
}

这使得调用端点变得非常简单,并最大限度地减少重复代码。

// Get data from the API
ApiData.get('items', itemController.params)
    .then(function(data) {
        itemController.data = data;
    }
);