我在这里迈出了第一步,有两件事让我头疼。第一个问题是我无法将视图中的变量传递给http.post调用。
在这个index.html中,ng-click
传递正确的值:
<tbody>
<tr ng-repeat="data in filtered = (list | filter:search | orderBy : predicate :reverse) | startFrom:(currentPage-1)*entryLimit | limitTo:entryLimit">
<td><a href="{{data.link}}" target="_blank">{{data.songName}}</td>
<td>{{data.artist}}</td>
<td><a ng-click="deleteSong(data.songName, data.artist, data.link)"><i class="glyphicon glyphicon-trash"></i></a></td>
</tr>
</tbody>
在app.js中,deleSong函数如下所示:
$scope.deleteSong = function($songName, $artist, $link) {
// Posting data to php file
$http({
method : 'POST',
url : 'ajax/deleteSong.php',
data : $scope.data, //forms user object
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
// Showing errors.
$scope.errorSong= data.errors.song;
$scope.errorArtist= data.errors.artist;
$scope.errorLink= data.errors.link;
} else {
$scope.message = data.message;
}
});
$scope.user = null
}
最后,deleteSong.php看起来是这样的:
<?php
include('../includes/config.php');
$errors = array();
$data = array();
// Getting posted data and decodeing json
$_POST = json_decode(file_get_contents('php://input'), true);
$song = $_POST['song'];
$query="DELETE FROM songs WHERE songName = '$song'";
$mysqli->set_charset('utf8mb4');
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
echo $query;
?>
当我点击删除歌曲图标时,函数会被调用,但我得到的响应是:
DELETE FROM songs WHERE songName = ''
知道我缺少什么吗?为什么查询没有得到我传递给deleteSong.php
的数据?
更改代码如下,您将数据作为ng-clik函数的参数。但你没有使用这些。相反,您正在尝试$scope.data(这是另一回事)。因此,按如下方式更改代码。
$scope.deleteSong = function($songName, $artist, $link) {
// Posting data to php file
$http({
method : 'POST',
url : 'ajax/deleteSong.php',
data : {'song':$songName},//Changed Line Here
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
// Showing errors.
$scope.errorSong= data.errors.song;
$scope.errorArtist= data.errors.artist;
$scope.errorLink= data.errors.link;
} else {
$scope.message = data.message;
}
});
$scope.user = null
}
您正在将$_POST['song']分配给$song变量,但它不存在于$_POST-数组中。请用$_POST['songName']
替换$_POST['song']
这是一个已知的问题,在php文件中,不要使用$_POST
,而是尝试使用$data = json_decode(file_get_contents("php://input"));
(看这里)
假设其余的都没有bug,这可能会奏效。。。使用console.log确保$songName、$artist、$link变量包含正确的值。。。
请注意,永远不要将变量与$
一起使用,因为美元用于私有angularjs变量