【问题标题】:Reading content of $http in PHP在 PHP 中读取 $http 的内容
【发布时间】:2015-04-04 05:12:51
【问题描述】:

我正在向服务器发送数据如下:

$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']) 但这也给出了空白

【问题讨论】:

  • 也许先解码整个响应?在获取数组元素之前。
  • $http 服务不会对您的数据进行开箱即用的 urlencode。见:见:stackoverflow.com/questions/11442632/…
  • 或者,使用php://input 流和json_decode 其内容。

标签: php json angularjs


【解决方案1】:

需要对data中的参数进行formencode:

$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;
    });
  }});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多