【问题标题】:How to Post Array multidimensional angular js如何发布数组多维角度js
【发布时间】:2017-01-02 21:08:21
【问题描述】:

我在 angularjs 中有一个数组,示例如下。

$scope.order.qty='20';
$scope.order.adress='Bekasi';
$scope.order.city='Bekasi';

这个数组可以用这个代码发布

$http({
          method  : 'POST',
          url     : '<?php echo base_url(); ?>add_order',
         data    : $scope.order,
          headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
         })

我可以使用

获取所有变量
$_POST = json_decode(file_get_contents('php://input'), true);
$_POST['qty'];
$_POST['address'];
$_POST['city'];

但如果数组像这样多维,我会感到困惑:

$scope.items[1].kode_produk='PR_1';
$scope.items[2].kode_produk='PR_2';
$scope.items[3].kode_produk='PR_3';

如何像这样从多维数组中发布和获取变量?

【问题讨论】:

    标签: javascript php angularjs arrays multidimensional-array


    【解决方案1】:

    如果您发送$scope.items,您的 json 将如下所示:

    [
      {
        "kode_produk": "PR_1"
      },
      {
        "kode_produk": "PR_2"
      },
      {
        "kode_produk": "PR_3"
      }
    ]
    

    $input = json_decode(...) 之后这个 php 数组的结果:

    array (size=3)
      0 => 
        object(stdClass)[1]
          public 'kode_produk' => string 'PR_1' (length=4)
      1 => 
        object(stdClass)[2]
          public 'kode_produk' => string 'PR_2' (length=4)
      2 => 
        object(stdClass)[3]
          public 'kode_produk' => string 'PR_3' (length=4)
    

    你有一个对象数组,而不是多维数组!

    您可以遍历以下项目:

    foreach($input as $item)
    {
        echo $item->kode_produk;
    }
    

    【讨论】:

      【解决方案2】:

      是一种方式

      在JavaScript中发送数据$scope.items,例如:

      $http({
                method  : 'POST',
                url     : '<?php echo base_url(); ?>add_order',
               data    : $scope.items,
                headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
               })
      

      并在网站上写 PHP 代码:

      $_POST = json_decode(file_get_contents('php://input'), true);
      var_dump($_POST); die();
      

      并分析数据结构。

      【讨论】:

        【解决方案3】:

        你可以像这样传递数组:

        $http({
              method  : 'POST',
              data    : { items: $scope.items }
              ...
             })
        

        获取数据:

        $_POST = json_decode(file_get_contents('php://input'), true);
        $items = $_POST['items'];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-11
          • 2016-08-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-12
          相关资源
          最近更新 更多