【问题标题】:How to send array data via $http POST and Parse the same in PHP?如何通过 $http POST 发送数组数据并在 PHP 中解析相同的数据?
【发布时间】:2018-04-26 09:03:14
【问题描述】:
var send=[];

// send[] data contains:
// [{"host":"1","name":"2","password":"3"},
//  {"host":"4","name":"5","password":"6"},
//  {"host":"7","name":"8","password":"9"},
//  {"host":"10","name":"11","password":"12"}]

$http({
        method: 'POST',
        url: 'file.php',
        data: send,
        headers: {
          'Content-Type': 'Content-type: application/json'
        },

      }).
      success(function(response) {}).
      error(function(response) {});

      return false;
    };

我在发送数据时遇到错误,我无法使用 $_POST 解析这些数据。我尝试过以下操作:

var obj=(JSON.stringify(send));
data:obj,

在我的 PHP 文件中:

$request = file_get_contents('php://input');
                 $data=json_decode($request);
                 print_r($data);

【问题讨论】:

  • 您遇到了什么错误? (有$http.post("file.php", send).then(function(response){ ... })就够了)你也可以尝试用echo json_encode($data)返回数据
  • 来自本地主机:
    通知:未定义索引:/Applications/XAMPP/xamppfiles/htdocs/try/parse.php 中的名称上线2

    注意:未定义索引:/Applications/XAMPP/xamppfiles/htdocs/try/parse.php中的密码 第 3 行

  • 这就是我得到的响应,当我这样做时
    success(function(response) { window.alert(response);
  • 您使用的是 Mac 吗?您不应该使用MAMP 本地服务器而不是XAMPP 吗?但这绝对是后端问题
  • 如果您将'Content-Type': 'Content-type: application/json' 更改为'Content-Type': 'application/json',您的代码是否有效

标签: javascript php arrays angularjs json


【解决方案1】:

如果您想检索已发布的数据,请使用$_POST['data']

$request = $_POST['data'];
$data = json_decode($request);
print_r($data); 

您能否详细说明“我遇到错误”是什么意思?

【讨论】:

  • 来自本地主机:
    通知:未定义索引:/Applications/XAMPP/xamppfiles/htdocs/try/parse.php 中的名称上线2

    注意:未定义索引:/Applications/XAMPP/xamppfiles/htdocs/try/parse.php中的密码 第 3 行

  • 这就是我得到的响应,当我这样做时
    success(function(response) { window.alert(response);
  • 显示您发布的数据,您可以通过print_r $_POST['data']; exit; 进行操作并查看ajax 响应,
  • 我没有投反对票,但这是错误的。在 JavaScript 代码中没有任何地方使用名为 data 的“post 变量”。
  • AngularJS-> $http({ method: method, url: url, data: FormData, headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
猜你喜欢
  • 2010-12-12
  • 2012-11-14
  • 1970-01-01
  • 1970-01-01
  • 2011-12-13
  • 2014-04-12
  • 2012-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多