在PHP中读取$ http的内容

时间:2015-04-04 05:12:52

标签: php json angularjs

我将数据发送到服务器,如下所示:

$scope.saveCaption = function(user_id) {
  var target = document.getElementById('toRender');
      html2canvas(target, {
        onrendered: function(canvas) {
    $http({
      url: "/production/save.php?user_id="+user_id,
      method: "POST",
      headers: {
        'Content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        //image: canvas.toDataURL("image/png"), // commented out for testing only
        news: 'test'
        }
    }).success(function(data, status, headers, config) {
      console.log('success');
      $scope.data = data;
    }).error(function(data, status, headers, config) {
      console.log('failed');
      $scope.status = status;
    });
  }});
}

尝试用PHP阅读 - save.php

$data = $_POST['news'];
echo "data is $data"; die;

问题是$_POST['news']总是空白的?

这是发送的数据:

{"news":"test"} 

注意它的JSON,但我特意尝试更改内容类型:

'Content-type': 'application/x-www-form-urlencoded'

那么如何发送普通数据而不是JSON呢?或者,我怎样才能让php正确地阅读JSON,我尝试$data = json_decode($_POST['news'])但是这也是空白

1 个答案:

答案 0 :(得分:1)

您需要在数据中对参数进行格式编码:

$scope.saveCaption = function(user_id) {
  var target = document.getElementById('toRender');
      html2canvas(target, {
        onrendered: function(canvas) {
    $http({
      url: "/production/save.php?user_id="+user_id,
      method: "POST",
      headers: {
        'Content-type': 'application/x-www-form-urlencoded'
      },
      data: 'news=test', // form encoded
    }).success(function(data, status, headers, config) {
      console.log('success');
      $scope.data = data;
    }).error(function(data, status, headers, config) {
      console.log('failed');
      $scope.status = status;
    });
  }});
}