我有一个 Angular + PHP 应用程序,但在删除客户时遇到问题。
我没有收到任何错误,实际上,应用程序返回了成功,但它并没有从我的数据库中删除客户。
这是我的 Angular Controller
app.controller('consultar_cliente_controller', function($scope, $http){
$scope.listaDeCliente = [];
var init = function(){
$scope.buscar();
};
$scope.buscar = function(){
$http.get('consultar_cliente.php')
.success(function(data){
$scope.listaDeCliente = data;
})
.error(function(){
console.error('Erro ao executar o GET do cliente');
});
};
$scope.deletar = function(id){
$http.delete('remover_cliente.php/' + id)
.success(function(){
console.log('Cliente removido com sucesso!');
$scope.buscar();
})
.error(function(){
console.error('Erro ao remover cliente');
})
};
init();
});
这是我的PHP
<?php
$dbh = new PDO('pgsql:host=localhost;dbname=livraria_glp', 'postgres');
/*
* Recuperando todos os detalhes da requisição HTTP do Angular
*/
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
@$id = $request->id;
echo $id;
$dbh->exec("DELETE FROM PRODUTO WHERE ID = '$id'") or die( $dbh->errorInfo() );
?>
这是我的 HTML
<div class="well">
<div class="container">
<h2>Dados</h2>
<div class="form-group">
<label>Nome</label>
<input class="form-control" type="text" ng-model="filtroNome" />
</div>
</div>
<div class="container resultado">
<table class="table">
<thead>
<tr>
<th>Nome</th>
<th>CPF</th>
<th>E-mail</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="cliente in listaDeCliente | filter : filtroNome">
<td>{{cliente.nome}}</td>
<td>{{cliente.cpf}}</td>
<td>{{cliente.id}}</td>
<td><button class="btn btn-danger" ng-click="deletar(cliente.id)">Deletar</button></td>
</tr>
</tbody>
</table>
</div>
<button class="btn btn-success" onclick="window.location.href='javascript:window.history.go(-1)'">Voltar</button>
</div>
编辑:我已经在 PHP 上试过了:
echo "DELETE FROM PRODUTO WHERE ID = '$id'";
它返回:
从 ID = '' 的产品中删除
为什么PHP收不到id?
最佳答案
Angular 不会为 DELETE
发送请求主体,因此您将不得不从 URL 中读取 id
。您不妨将其作为查询参数传递
$http.delete('remover_cliente.php', {
params: {id: id}
})
然后通过$_GET['id']
读取。
<?php
if (!isset($_GET['id'])) {
exit;
}
$id = $_GET['id'];
$dbh = new PDO('pgsql:host=localhost;dbname=livraria_glp', 'postgres');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare('DELETE FROM PRODUTO WHERE ID = ?');
$stmt->execute([$id]);
echo $id;
或者(以防万一 $_GET
对 DELETE
请求不起作用),您可以尝试使用
$http.delete('remover_cliente.php', {
data: {id: id}
})
但是我不知道这是否受支持,而且它肯定不是很 REST-ful。如果确实有效,您可以继续使用 file_get_contents('php://input')
和 json_decode()
。
关于php - Angular - $http.delete 返回成功但不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30769961/