3
* CJavaScript helper class file.
5
* @author Qiang Xue <qiang.xue@gmail.com>
6
* @link http://www.yiiframework.com/
7
* @copyright Copyright © 2008-2011 Yii Software LLC
8
* @license http://www.yiiframework.com/license/
12
* CJavaScript is a helper class containing JavaScript-related handling functions.
14
* @author Qiang Xue <qiang.xue@gmail.com>
15
* @version $Id: CJavaScript.php 2799 2011-01-01 19:31:13Z qiang.xue $
16
* @package system.web.helpers
22
* Quotes a javascript string.
23
* After processing, the string can be safely enclosed within a pair of
24
* quotation marks and serve as a javascript string.
25
* @param string $js string to be quoted
26
* @param boolean $forUrl whether this string is used as a URL
27
* @return string the quoted string
29
public static function quote($js,$forUrl=false)
32
return strtr($js,array('%'=>'%25',"\t"=>'\t',"\n"=>'\n',"\r"=>'\r','"'=>'\"','\''=>'\\\'','\\'=>'\\\\','</'=>'<\/'));
34
return strtr($js,array("\t"=>'\t',"\n"=>'\n',"\r"=>'\r','"'=>'\"','\''=>'\\\'','\\'=>'\\\\','</'=>'<\/'));
38
* Encodes a PHP variable into javascript representation.
42
* $options=array('key1'=>true,'key2'=>123,'key3'=>'value');
43
* echo CJavaScript::encode($options);
44
* // The following javascript code would be generated:
45
* // {'key1':true,'key2':123,'key3':'value'}
48
* For highly complex data structures use {@link jsonEncode} and {@link jsonDecode}
49
* to serialize and unserialize.
51
* @param mixed $value PHP variable to be encoded
52
* @return string the encoded string
54
public static function encode($value)
58
if(strpos($value,'js:')===0)
59
return substr($value,3);
61
return "'".self::quote($value)."'";
63
else if($value===null)
65
else if(is_bool($value))
66
return $value?'true':'false';
67
else if(is_integer($value))
69
else if(is_float($value))
72
return 'Number.NEGATIVE_INFINITY';
74
return 'Number.POSITIVE_INFINITY';
76
return rtrim(sprintf('%.16F',$value),'0'); // locale-independent representation
78
else if(is_object($value))
79
return self::encode(get_object_vars($value));
80
else if(is_array($value))
83
if(($n=count($value))>0 && array_keys($value)!==range(0,$n-1))
85
foreach($value as $k=>$v)
86
$es[]="'".self::quote($k)."':".self::encode($v);
87
return '{'.implode(',',$es).'}';
92
$es[]=self::encode($v);
93
return '['.implode(',',$es).']';
101
* Returns the JSON representation of the PHP data.
102
* @param mixed $data the data to be encoded
103
* @return string the JSON representation of the PHP data.
105
public static function jsonEncode($data)
107
return CJSON::encode($data);
111
* Decodes a JSON string.
112
* @param string $data the data to be decoded
113
* @param boolean $useArray whether to use associative array to represent object data
114
* @return mixed the decoded PHP data
116
public static function jsonDecode($data,$useArray=true)
118
return CJSON::decode($data,$useArray);