在前台中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"));