简体   繁体   English

如何将JSON数组从php传递到JS?

[英]How can i pass a JSON array from php to JS?

im trying to populate a morris.js chart from a set of results. 我试图从一组结果中填充morris.js图表​​。 In my controller I create an array of the results and use json_encode to create a json array, here is the output in my view using print_r: 在我的控制器中,我创建一个结果数组,并使用json_encode创建一个json数组,这是在我的视图中使用print_r的输出:

{"Positive":7,"Negative":26,"Pending":786,"Contact the Clinic":242,"Misc":2} 

How would I pass this to my morris.js chart to populate the chart using this data as label / value pairs? 如何将其传递到morris.js图表​​以使用此数据作为标签/值对填充图表? everything I try I get either a blank chart or an "undefined" variable or "NaN". 我尝试的所有操作都会得到空白图表或“未定义”变量或“ NaN”。 Here is my controller: 这是我的控制器:

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);
}

and my morris.js: 和我的morris.js:

$results = "<?php echo $chart ?>";
new Morris.Donut({
    element: 'donutEg',
    data: [
        $results
    ],
});

Any help is greatly appreciated 任何帮助是极大的赞赏

Assuming that your morris.js is a normal javascript file, you cannot use php there by default: The server will not parse the .js file so the php source code will appear in your javascript. 假设您的morris.js是正常的javascript文件,则默认情况下无法在其中使用php:服务器不会解析.js文件,因此php源代码将出现在javascript中。

You need to either: 您需要:

  • Put the morris.js script contents in a php page in a javascript block so that the php gets parsed; morris.js脚本内容放在javascript块的php页面中,以便对php进行解析;
  • Make an ajax request from your morris.js script to get the data from the server in a separate request; morris.js脚本发出ajax请求,以单独请求从服务器获取数据;
  • Set up your server to parse .js files as if they are / contain php. 设置您的服务器以解析.js文件,就好像它们是/包含php。

The last one is just to illustrate what you would need, I would not recommend doing that. 最后一个只是为了说明您的需求,我不建议您这样做。

In javascript, JSON.parse is your friend, assuming you have JSON that was created by PHP's json_encode function: 在javascript中,假设您有由PHP的json_encode函数创建的JSON,则JSON.parse是您的朋友:

$results = "<?php echo $chart ?>";
new Morris.Donut({
    element: 'donutEg',
    data: [
        JSON.parse( $results )
    ],
});

OR POSSIBLY 或可能

$results = "<?php echo $chart ?>";
new Morris.Donut({
    element: 'donutEg',
    data: JSON.parse( $results )
});

BUT THE WAY I DO IT 但是我做的方式

In the view: 在视图中:

<input type="hidden" id="chartData" value='<?php echo $chart; ?>' />

In the JS (using jQuery): 在JS中(使用jQuery):

var chartData = $('#chartData').val();
new Morris.Donut({
    element: 'donutEg',
    data: JSON.parse( chartData )
});

After looking at the documentation for morris.js, I found that this is how you can do it the right way: 查看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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM