【问题标题】:JavaScript associative array to PHPJavaScript 关联数组到 PHP
【发布时间】:2012-05-14 12:51:29
【问题描述】:

'我有 JavaScript 关联数组名称'options'

<script>
options[dynamickey] = Number; 
</script>

我只想使用 jQuery post 将此数组发送到 codeigniter 模型

<script>
$.('link',options);
</script>

但问题是我不知道如何提取这个数组的每个键和值(选项)。 我的带有数据的 JavaScript 数组看起来像这样

 <script>
  options { 
     id => 135,
     'Chestnut' => 11,
     'Cinamon' => 1
   }
</script>

在 codeigniter (PHP) 模型中,我只想像这样提取这个数组

<?php
 $id = $this->input->post('id');
//below variable names and data should be dynamic from that javascript array
$chesnut= $this->input->post('dynamic value');
?>

请帮我解决这个问题。

【问题讨论】:

  • 你怎么能发布到你的模型!!你需要一个控制器方法来处理这个
  • 是的,我有控制器,但在我的帖子中我只是忽略了那一步
  • 请注意,JavaScript doesn't have associative arrays。您有一个带有属性的 JavaScript 对象。如果您尝试遍历项目或对“数组”进行 json 编码,这将变得很重要,因为这取决于您创建它的方式,它可能会失败或具有额外的神秘值。

标签: php javascript jquery arrays codeigniter


【解决方案1】:

在你的 jQuery 中,你做一个帖子:

var options = { 
    'id' : 135,
    'Chestnut' : 11,
    'Cinamon' : 1
}

$.post('example.com/index.php/firstsegment/secondsegment',options,function(data){...});

在接收此帖子的 CodeIgniter 控制器中:

public firstsegment extends CI_Controller {

    public function secondsegment(){
        $data = $this->input->post();

        if($data){
            /*
            $data will contain this:
            $data = array(
                'id' => '135',
                'Chestnit' => '11',
                'Cinamon' => '1'
            );
            */
        }
    }
}

【讨论】:

    【解决方案2】:

    坦率的要求很少见。您想要将您的系统可能呈现的内容发送到您的系统吗?

    尽管如此。在jQuery ajax 中添加{ data : options } 以及现有的常用值。

    示例:

    var options = { 
        'id' : 135,
        'Chestnut' : 11,
        'Cinamon' : 1
    }
    
    $.ajax({
      type: "POST",
      url: "some.php",
      data: options
    }).done(function( msg ) {
      alert( "Data Saved: " + msg );
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 2012-09-12
      • 2014-08-22
      相关资源
      最近更新 更多