Angular js,在选择元素上,我想 POST 数据以将其保存在数据库中,然后我想使用 PUT 更新它而无需重新加载

Angular js, on select element i want to POST data to save it in the database then i want to update it with PUT without page reload

本文关键字:更新 PUT 加载 新加载 我想 POST 元素 选择 js 数据 数据库      更新时间:2023-09-26

我有一个表中有一个选择字段,如果它通过 POST 数据不存在,我想将其保存到数据库中。如果它确实存在,那么我想更新数据库中已经存在的行。这可以在我有带有 ng-repeat 的表行以显示来自 json 的所有数据的 tbody 中找到。

<td>
  <select id="statusSelect{{anime.id}}" ng-model="statusId" ng-options="animeStatus.id as animeStatus.status for animeStatus in animeStatuses"
      ng-change='addUserAnime( "<?php echo Yii::app()->user->id; ?>", anime.id, statusId )'>
  </select>
</td>

接下来,这是我在角度控制器中尝试执行的操作的代码:

$scope.addUserAnime = function( userId, animeId, statusId, userAnime )
{
    if ( userId == '' ) {
        //alert user that he/she needs to log in first
    } else {
        //loop through my json where i saved from which user which anime is saved with which status
        for (var i = 0; i < $scope.usersAnime.length; i++) {
            //if there is an already existing entry then i want to update it if not then i want to introduce it into DB with POST
            if ($scope.usersAnime[i].anime_id == animeId && $scope.usersAnime[i].user_id == userId) {
                $scope.userAnime = $.extend({}, $scope.usersAnime[i]);
                $scope.userAnime.status_id = statusId;
                $scope.userAnime.date_modified = today;
                saveUserAnime();
                return;
            }
        }
        $scope.userAnime = {
            id: 0,
            user_id: userId,
            anime_id: animeId,
            status_id: statusId,
            rating: '',
            date_modified: today
        };
        saveUserAnime();
    }
};
问题是,如果我发布一个新条目,它会

保存在数据库中,但是如果我不重新加载页面并且再次更改选择给它一个新选项,它会再次发布而不是使用 PUT 进行更新。最后,我最终得到了两个条目而不是一个条目。我想在第一次选择时将其引入数据库,如果之后更改,我想更新它。这可能吗。我尝试使用表格作为表格$dirty来做到这一点,但这是一个诺诺。在saveUserAnime()函数中,如果它是新条目,则正确定义为使用POST,如果它是现有条目,则使用PUT。我有另一种形式可以工作。问题必须出在此当前函数中。

只需将该代码放在获取带有animeStatus的对象的位置,然后将其放入函数中,然后直接调用它。现在,您可以在 POST 完成后调用该函数,以便加载新数据。

否则,您也可以通过SQL进行检查,如果表中存在该值,因此您不需要在angularjs中签入,这将比这个更容易。