使用angularjs,php和mysql$http帖子后刷新表


Refresh table after $http post using angularjs, php and mysql

我需要刷新表以显示从方法发送数据后$http新添加的行。以下是我用于将表单值添加到 mysql 表的工作代码。如果有人可以帮助我以棱角分明的方式实现这一目标,我们将不胜感激。

JS代码:

var myApp = angular.module('myApp', ['ngRoute']);
myApp.controller('bookmarkCtrl', function($scope, $http) {
$scope.addThis = function() {
$http({
  url: "addbookmark.php",
  method: "POST",
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  data: $.param({
    bookmarktitle: $scope.bookmarktitle,
    bookmarkurl: $scope.bookmarkurl
  })
}).success(function(data, status, headers, config) {
    //refresh the table after success
}).error(function(data, status, headers, config) {
});
}
});

.HTML

<div class="panel-body" ng-app="myApp" ng-controller="bookmarkCtrl">
<input ng-model="bookmarktitle" type="text" class="form-control" required>
<input  ng-model="bookmarkurl" type="text" class="form-control">
<button type="button" class="btn btn-default" ng-click="addThis();">Submit</button>

<table class="table table-responsive">
<thead>
  <tr>
    <th>...</th>
  </tr>
</thead>
<tbody>
   <!-- repeat row -->
    <tr>
      <td>
        <?php echo $row['bookmark_title'] ?>
      </td>
    </tr>
   <!-- repeat row -->
</tbody>
</table>
</div>

@ismailvtl,Angular 是一个客户端库,因此通常数据将通过来自客户端的 ajax 调用进行填充。 为了动态添加行,控制器必须可以访问数据。

$scope.bookmarks = [];
$scope.getBookmarks = function() {
    $http.get('/bookmarks').then(function(response) {
        // should do validation here
        $scope.bookmarks = response.data
    }
}
$scope.getBookmarks();

然后,在你的 html 中,它应该看起来像

...
<tr ng-repeat="bookmark in bookmarks">
    <td>{{bookmark.bookmarktitle}}</td>
<tr>
...

然后,最后,在你的addThis()函数中:

$scope.addThis = function() {
    $http({
       url: "addbookmark.php",
       method: "POST",
       headers: {
         'Content-Type': 'application/x-www-form-urlencoded'
       },
       data: $.param({
         bookmarktitle: $scope.bookmarktitle,
         bookmarkurl: $scope.bookmarkurl
       })
   }).success(function(data, status, headers, config) {
       var bookmark = { 
         bookmarktitle: data.bookmarktitle,
         bookmarkurl: data.bookmarkurl
        }
        $timeout(function() {
            $scope.bookmarks.push(bookmark)
        }
   }).error(function(data, status, headers, config) {
       // handle error here
   });
}

或者,您可以使用 ng-init 直接在 php 的视图中分配书签数组(类似于 php 提供的值ng-init="bookmarks=[{bookmarktitle: 'titlea',bookmarkurl: 'urla'},...]"