[英]How can i pass a JSON array from php to JS?
我試圖從一組結果中填充morris.js圖表。 在我的控制器中,我創建一個結果數組,並使用json_encode創建一個json數組,這是在我的視圖中使用print_r的輸出:
{"Positive":7,"Negative":26,"Pending":786,"Contact the Clinic":242,"Misc":2}
如何將其傳遞到morris.js圖表以使用此數據作為標簽/值對填充圖表? 我嘗試的所有操作都會得到空白圖表或“未定義”變量或“ NaN”。 這是我的控制器:
function execute_search()
{
// Retrieve the posted search term.
$search_term = $this->input->post('search');
// Get results count and pass it as json:
$data = $this->search_model->count_res('$p_results_data');
$pos = 0; $neg= 0; $pen = 0; $cont = 0; $misc = 0;
foreach ($data as $item) {
if ($item['result'] === 'Positive') {
$pos++;
} elseif ($item['result'] === 'Negative') {
$neg++;
} elseif ($item['result'] === 'Pending') {
$pen++;
} elseif ($item['result'] === 'Contact the Clinic') {
$cont++;
} else {
$misc++;
}
}
$res = array("Positive"=>$pos, "Negative"=>$neg, "Pending"=>$pen, "Contact the Clinic"=>$cont, "Misc"=>$misc);
$data = json_encode($res);
// Use the model to retrieve results:
$this->data['results'] = $this->search_model->get_results($search_term);
$this->data['chart'] = $data;
$this->data['totals'] = $this->search_model->total_res('$total_res');
// Pass the results to the view.
$this->data['subview'] = ('user/search_results');
$this->load->view('_layout_admin', $this->data);
}
和我的morris.js:
$results = "<?php echo $chart ?>";
new Morris.Donut({
element: 'donutEg',
data: [
$results
],
});
任何幫助是極大的贊賞
假設您的morris.js
是正常的javascript文件,則默認情況下無法在其中使用php:服務器不會解析.js
文件,因此php源代碼將出現在javascript中。
您需要:
morris.js
腳本內容放在javascript塊的php頁面中,以便對php進行解析; morris.js
腳本發出ajax請求,以單獨請求從服務器獲取數據; .js
文件,就好像它們是/包含php。 最后一個只是為了說明您的需求,我不建議您這樣做。
在javascript中,假設您有由PHP的json_encode函數創建的JSON,則JSON.parse是您的朋友:
$results = "<?php echo $chart ?>";
new Morris.Donut({
element: 'donutEg',
data: [
JSON.parse( $results )
],
});
或可能
$results = "<?php echo $chart ?>";
new Morris.Donut({
element: 'donutEg',
data: JSON.parse( $results )
});
但是我做的方式
在視圖中:
<input type="hidden" id="chartData" value='<?php echo $chart; ?>' />
在JS中(使用jQuery):
var chartData = $('#chartData').val();
new Morris.Donut({
element: 'donutEg',
data: JSON.parse( chartData )
});
查看morris.js的文檔后,我發現這是正確的方法:
// Looking at the docs for morris.js:
// http://jsbin.com/ukaxod/144/embed?js,output
// This is your data, but it's all in one json object
var chartData = JSON.parse( $('#chartData').val() );
// We need to break up that object into parts of the donut
var donutParts = [];
$.each( chartData, function(k,v){
donutParts.push({
label: k,
value: v
});
});
// Now create the donut
Morris.Donut({
element: 'donutEg',
data: donutParts
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.