【问题标题】:How can Angularjs send value of checked checkbox to .php?Angularjs如何将选中复选框的值发送到.php?
【发布时间】:2015-09-27 19:56:10
【问题描述】:

我只想保存多个复选框中包含的值,前提是它们被选中。它们将使用 php 保存到 MySQL 数据库中。这是我的 HTML 代码。

<div class="panel" ng-controller="checkBoxController"> 
    <input class="form-control" placeholder="Cherchez vos contacts" type="text" ng-model="searchText">
    </br>
    <div ng-repeat="employee in employees | filter:searchText ">
        <label class="action-checkbox">
            <input id="{{employee.name}}" type="checkbox" value="{{employee.name}}" ng-checked="selection.indexOf(employee.name) > -1" ng-click="toggleSelection(employee.name)">
        </label>
        <label for="{{employee.name}}"></label>
            {{employee.name}}
        </label>
    </div>
    </br>
    <span class="selected-item">Destinataires choisis:<span>
    <div ng-repeat="name in selection" class="selected-item">
        {{name}}
    </div>
</div>

这是我的 JS 代码。

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

myApp.controller('checkBoxController', function($scope, $http) {
    $http.get("information.php")
        .success(function (response) {
            $scope.employees = response.records;
        }); 

    $scope.selection = [];

    // toggle selection for a given employee by name
    $scope.toggleSelection = function toggleSelection(employeeName) {
        var idx = $scope.selection.indexOf(employeeName);

        if (idx > -1) {
            $scope.selection.splice(idx, 1);
        } else {
            $scope.selection.push(employeeName);
        }
    };
});

下一步是什么?也许保存在 JSON 文件中并通过 HTTP post 发送?我迷路了。

【问题讨论】:

  • 您使用 $http.get 从 php 获取员工数据。您可以使用$http.post 将数据发送到 php。所以基本上以$http.post("myfile.php", {selection: $scope.selection}) 为例。
  • 您可以简单地收集表单数据并将其发送到所需的 php 文件,然后执行插入检查这个小提琴jsfiddle.net/YGQT9
  • 对不起,我试过了,但我在我的 php 页面中收到了注释。

标签: javascript php mysql angularjs


【解决方案1】:

您所要做的就是拥有一个可以接受 JSON 并将您的数组从控制器中的函数发送给它的端点。

$scope.sendSelection = function() {
    $http.post('your/url.php', { selection: $scope.selection })
        .success(function(data) {
            // Handle success.
        })
        .error(function(err) {
            // Handle error.
        });
}

然后有一个按钮在你的 HTML 中发送它:

<button data-ng-click="sendSelection()">Save Selections</button>

让 PHP 文件接收和处理 JSON 数组完全是另一回事。

【讨论】:

  • 我还有其他信息要发送,所以我使用
    我写 提交,但我仍然无法收到复选框的信息,这是我的代码 php $data = json_decode(file_get_contents("php://input")); print_r ($data);有错吗?
  • 提交表单时会出现什么? print_r($data); 的输出应该会引导您朝着正确的方向前进。
  • 对于您的表单,您不需要提交按钮上的 ng-click 事件,因为您没有使用 Angular 来提交它。要么这样,要么你需要在 sendSelection 函数中包含表单中的所有内容并使用 $http.post 并查看 data 在提交时是什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 2015-05-18
  • 1970-01-01
相关资源
最近更新 更多