AJAX传递数组

在前台中Jq代码中中用JSON.stringify()将数组转换成 JSON字符串、在后台用json_decode()将JSON字符串转换成数组.

1、JSON.stringify(value [, replacer] [, space])

  value:是必选字段。为对象、数组、类等。

 replacer:是可选字段。它又分为2种方式,一种是数组,第二种是方法。

   情况一:replacer为数组时,它是和第一个参数value有关系的。一般来说,系列化后的结果是通过键值对来进行表示的。 所以,如果此时第二个参数的值在第一个存在,那么就以第二个参数的值做key,第一个参数的值为value进行表 示,如果不存在,就忽略。

  情况二:replacer为方法时,那很简单,就是说把系列化后的每一个对象(记住是每一个)传进方法里面进行处理。

space:是可选字段。是什么做分隔符。

2、json_decode()

json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

 json:待解码的 json string 格式的字符串。

assoc:当该参数为 TRUE 时,将返回array 而非object

depth:用户指定递归深度。

options:JSON位掩码选项。

3、例子

   前台 :

             var arr=new Array(1,2,3);

                   var operatorIDs=JSON.stringify(arr);//将数组转为JSON字符串

                        $.ajax({
                            type: 'post',
                            data: {'text':text, 'operatorIDs':operatorIDs },
                            url: '<?php echo $this->createUrl('letter/SendLetters');?>',
                            success: function (data) {
                               alert(data);
                            }

  后台:

            $model->operatorIDs= json_decode(Yii::app()->request->getParam("operatorIDs"));

原文地址:https://www.cnblogs.com/huixuexidezhu/p/5053443.html