2017-05-24 50 views
0

我正在使用angularjs 1.6.4版本,我发送我的密钥和值到php web服务,但我的密钥和值不读取,我得到的数据库结果存储在' 0' ,这是我的角度js代码,php的web服务无法读取我的角度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

你的问题是AngularJS相关,而不是Angular。允许我编辑您的帖子。 – trichetriche

回答

0

它看起来像你可能会将字符串保存为数字字段DS。当调用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()并保存空值而不是空字符串,这应该解决这个问题。