简体   繁体   English

从PHP发送数组到jQuery

[英]sending array from php to jquery

how do i pass an array from php to jquery both are in same file , i just have an array named $array2 with data that will be used to make graph below code is using chartdata but i want to use variable from my php script 我如何将数组从php传递到jquery都在同一个文件中,我只是有一个名为$ array2的数组,其数据将用于使下面的图成为图形,代码正在使用chartdata,但是我想从我的php脚本中使用变量

 <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
var chart;

var chartData = [{
    student: 5,
    marks: 0},
{
    student: 8,
    marks: 50},
{
    student: 10,
    marks: 100}];


AmCharts.ready(function() {
    // SERIAL CHART
    chart = new AmCharts.AmSerialChart();
    chart.dataProvider = chartData;
    chart.categoryField = "marks";
    chart.startDuration = 1;

    // AXES
    // category
    var categoryAxis = chart.categoryAxis;
    categoryAxis.labelRotation = 90;
    categoryAxis.gridPosition = "student";

    // value
    // in case you don't want to change default settings of value axis,
    // you don't need to create it, as one value axis is created automatically.
    // GRAPH
    var graph = new AmCharts.AmGraph();
    graph.valueField = "student";
    graph.balloonText = "[[category]]: [[value]]";
    graph.type = "column";

    graph.lineAlpha = 0;
    graph.fillAlphas = 8.4;
    chart.addGraph(graph);

    chart.write("chartdiv");
});
 </script>

you can use json data to pass php to jquery. 您可以使用json数据将php传递给jquery。

in php 在PHP中

$php_data = json_encode($your_php_data_in_array);

assigning to jquery 分配给jQuery

var data = <?php echo $php_data ;?>

getting the value in jquery 在jQuery中获取值

var chart_data_arr = json_decode(data);

now you have the data in array in jquery. 现在,您在jquery中将数据放入数组中。

The simplest (and not necessarily the most scure/efficient/modular/blah blah) possible way you can just dump it using json_encode 您可以使用json_encode转储它的最简单(不一定是最安全/高效/模块化/等等)的方法

var chartData = [{
    student: 5,
    marks: 0},
{
    student: 8,
    marks: 50},
{
    student: 10,
    marks: 100}];

//Instead
var chartData=<?php echo json_encode($chartdata)?>

Alternately, you would pass it using a json action that will render the json at a certian link and use jquery to query this url and then generate the chart with that data. 或者,您将使用json操作传递它,该操作将在certian链接处呈现json,并使用jquery查询此url,然后使用该数据生成图表。

To use php data in javascript use:- 要在javascript中使用php数据,请使用:-

var javascriptVariable = <?php echo json_encode($php_array); ?>;

So javascriptVariable would become an object/array as per your php data. 因此,根据您的php数据,javascriptVariable将成为对象/数组。

Try this : 尝试这个 :

<?php 

  $your_php_array = array(.....);
?>
var chartData = <?php json_encode($your_php_array)?>;

ref: http://php.net/manual/en/function.json-encode.php 参考: http : //php.net/manual/en/function.json-encode.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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