我正在使用angularjs 1.6.4版本,我将我的密钥和值发送到php web服务但我的密钥和值没有读取,我得到的数据存储在' 0',这是我的角度js代码,
$scope.fav = {
"userid":101,
"favid":120
}
$http({
method:"POST",
url:apiurl+"addFavorites.php",
data:JSON.stringify($scope.fav)
}).then(function(data)
{
$scope.favorites = data.data;
alert(data.data.message);
});
这是我的php rest api
include("../includes/db.php");
//creating response array
$response = array();
$request_method = $_SERVER['REQUEST_METHOD'];
if ($request_method == 'POST' && array_key_exists('HTTP_X_HTTP_METHOD', $_SERVER)) {
if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'DELETE') {
$request_method = 'DELETE';
} else if ($_SERVER['HTTP_X_HTTP_METHOD'] == 'PUT') {
$request_method = 'PUT';
} else {
throw new Exception("Unexpected Header");
}
}
if($request_method == "POST"){
//getting values
$userid = isset($_POST['userid']) && $_POST['userid'] != '' ? trim($_POST['userid']) : "";
$favid = isset($_POST['favid']) && $_POST['favid'] != '' ? trim($_POST['favid']) : "";
if ($favid == 0) {
$strupdate = mysql_query("insert into nr_favourites(UserProfileId,FavouriteUserProfileId,CreatedDate)Values('$userid','$favid',now())");
}
if ($favid != 0) {
$sql = mysql_query("select * from nr_favourites where id=$favid");
$rc = mysql_num_rows($sql);
if ($rc != 0) {
$strupdate = mysql_query("insert into nr_favourites(UserProfileId,FavouriteUserProfileId,CreatedDate)Values('$userid','$favid',now())");
}
}
if ($strupdate)
{
$response['error']=false;
$response['message']='add favourites successfully!';
}
else
{
$response['error']=true;
$response['message']='add favourites not successfully.';
}
} else {
$response['error']=true;
$response['message']='You are not authorized';
}
header('Content-Type: application/json');
echo json_encode($response);
那些是我的代码,请帮我解决这个错误
答案 0 :(得分:0)
看起来您可能正在将字符串保存到数字字段中。调用JSON.stringify($scope.fav)
时,数字将转换为字符串。
这里
$userid = isset($_POST['userid']) && $_POST['userid'] != '' ? trim($_POST['userid']) : "";
$favid = isset($_POST['favid']) && $_POST['favid'] != '' ? trim($_POST['favid']) : "";
由于user_id和favid是字符串,因此每次都将它们设置为空字符串。我的猜测都是
nr_favourites.UserProfileId
nr_favourites.FavouriteUserProfileId
是接收字符串的数字字段,因此是0值。删除JSON.stringify()并保存空字符而不是空字符串,这应该解决问题。