php jquery中的json处理问题

php端传json:

1
2
3
4
$result['flag'] = 'ok';
$result['chart'] = Mage::helper('core')->jsonEncode($chart);
$result['description'] = 'fdsfdsf';
echo Mage::helper('core')->jsonEncode($result);

js端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
jQuery.ajax({
url: "<?php echo $this->getUrl('evaluator/adminhtml_theme/getStatsChart') ?>"+"?isAjax=true",
// dataType:'json',
type: "POST",
data: {cid:id,form_key:'<?php echo $this->getFormKey()?>'},
success: function(data){
data = jQuery.trim( data );
console.log(data);
/*
<span class="objectBox objectBox-text ">{"flag":"ok","chart":"{\"datasets\":[{\"label\":\"red\",\"fillColor\":\"rgba(220,220,220,0.2)\",\"strokeColor\":\"rgba(220,220,220,1)\",\"pointColor \":\"rgba(220,220,220,1)\",\"pointStrokeColor\":\"#fff\",\"pointHighlightFill\":\"#fff\",\"pointHighlightStroke\":\"rgba(220,220,220,1)\",\"data\":[11,28]},{\"label\":\"green\",\"fillColor\":\"rgba(220,220,220,0.2)\",\"strokeColor\":\"rgba(220,220,220,1)\",\"pointColor \":\"rgba(220,220,220,1)\",\"pointStrokeColor\":\"#fff\",\"pointHighlightFill\":\"#fff\",\"pointHighlightStroke\":\"rgba(220,220,220,1)\",\"data\":[16,39]}],\"labels\":[\"2014-09\",\"2014-10\"]}","description":"fdsfdsf"}</span>
*/
data = jQuery.parseJSON(data);
if(data.flag == 'ok'){
var chart = data.chart;
console.log(chart);
/*
<span class="objectBox objectBox-text "> {"datasets":[{"label":"red","fillColor":"rgba(220,220,220,0.2)","strokeColor":"rgba(220,220,220,1)","pointColor ":"rgba(220,220,220,1)","pointStrokeColor":"#fff","pointHighlightFill":"#fff","pointHighlightStroke":"rgba(220,220,220,1)","data":[11,28]},{"label":"green","fillColor":"rgba(220,220,220,0.2)","strokeColor":"rgba(220,220,220,1)","pointColor ":"rgba(220,220,220,1)","pointStrokeColor":"#fff","pointHighlightFill":"#fff","pointHighlightStroke":"rgba(220,220,220,1)","data":[16,39]}],"labels":["2014-09","2014-10"]}</span>
*/
//去掉key的双引号
chart=chart.replace(/"(\w+)"\s*:/g, '$1:');
console.log(chart);
/*
<span class="objectBox objectBox-text "> {datasets:[{label:"red",fillColor:"rgba(220,220,220,0.2)",strokeColor:"rgba(220,220,220,1)","pointColor ":"rgba(220,220,220,1)",pointStrokeColor:"#fff",pointHighlightFill:"#fff",pointHighlightStroke:"rgba(220,220,220,1)",data:[11,28]},{label:"green",fillColor:"rgba(220,220,220,0.2)",strokeColor:"rgba(220,220,220,1)","pointColor ":"rgba(220,220,220,1)",pointStrokeColor:"#fff",pointHighlightFill:"#fff",pointHighlightStroke:"rgba(220,220,220,1)",data:[16,39]}],labels:["2014-09","2014-10"]}</span>
*/
//转换为对象
chart = eval('(' + chart + ')');
/*注意:去掉双引号后,用jQuery.parseJSON会报错:SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data
,貌似只能用eval转换。
*/
});

 

 

坚持原创技术分享,您的支持将鼓励我继续创作!