• ECharts
      • Download js code
      • Analysis of working principle
      • Introduce ECharts into your project
    • Background processing
      • MySQL database
      • The PHP side
      • The JQuery Ajax handling
      • ECharts end processing
      • All front-end code
      • Results,
    • conclusion

Recently to the background database on some data in a visual method to display to the front end, find to find, baidu found the development of this chart tool library is good, online search about the relevant tutorials, is also a relatively simple demo. So write it down. Write it down.


ECharts

ECharts is a set of front-end charting tool library developed by Chinese people. It is super convenient and simple to use (of course, if you understand how it works).

Here’s a quick overview of how to use ECharts in your project.

Download js code

Download it from echarts.baidu.com

Personally, developers would be better off downloading the full version. And the official advice is to download the full version.

Bloggers here download the full version, about less than 2M.

Analysis of working principle

If you think about it, ECharts’ job is to display a particular image on a web page. So we need to realize that we need to give “pictures” a space so that they have a home.

And then you have space, you have land. To build a house, you have to have a frame. So you put some bricks and mortar on top of it to build the house. ECharts works the same way. But this skeleton is called Option. As for how this option needs to be set, there is a detailed introduction on the official website, the blogger will not repeat the wheel here. If you are interested, you can go to the place shown below.

Introduce ECharts into your project

As mentioned, this section Outlines how to use the icon library simply. Take a look at this code:


       
<html>
<head>
<meta charset="UTF-8">
<title>An introduction to</title>
<script src=".. /static/js/echarts.js"></script>
<script src=".. /static/js/sleeplib.js"></script>
</head>
<body>

    <h1>To begin testing</h1>
    <hr>
    <! Prepare a container for your chart -->
    <div id='container' style="width: 600px; height: 400px;"></div>
    <script>
        // Initialize an echarts instance with the echarts.init method and generate a simple bar graph with the setOption method

        // Instantiate the echarts instance based on the prepared DOM
        var myChart = echarts.init(document.getElementById("container"));

        // Specify the chart configuration items and data
        var option1 = {
            title : {
                text : 'Introduction to ECharts'
            },
            tooltip : {
                text : 'Mouse put up after the suspension prompt statement! '
            },
            legend : {
                data : [ 'sales' ]
            },
            xAxis : {
                data : [ 'shirt'.'Cardigan'.'Chiffon shirt'.'pants'.'High heels'.'socks'.'pants' ]
            },
            yAxis : {},
            series : [ {
                name : 'sales',
                type : 'bar',
                data : [ 7.20.36.10.10.20.28]]}};// Use the above configuration items as parameters and pass them to Echart to display
        myChart.setOption(option1);
    </script>
</body>
</html>Copy the code

The key is the last sentence:

myChart.setOption(option1);

It goes without saying that it works. So, what are the results? The diagram below:

In addition, manually click the small red rectangle with Legend as “Sales volume” above, you will be pleasantly surprised.


Now let’s get to the topic of the day


Background processing

Background processing involves querying the database using PHP and returning it as an array. JQuery retrieves the data in Ajax form and presents it to the front end for display.

MySQL database

Data is the core, so building a library is important. This is just for demonstration purposes, so the database setup is very simple, as shown below:

The PHP side

It is important to note that the database return must be JSON so that it can be easily handled by Ajax.

<? php header("Content-type=text/json; charset=UTF-8");

$conn = mysql_connect("localhost"."root"."mysql") or die("Database connection failed!");
mysql_query("set names utf-8");
mysql_select_db("test");


$resultset = mysql_query("select name, age from echartsuser", $conn);
////////////////////////////////////////////////Prepare data for loading
$data = array();
////////////////////////////////////////////////Entity class
class User{
    public $username;
    public $age;
}
////////////////////////////////////////////////To deal with
while($row = mysql_fetch_array($resultset, MYSQL_ASSOC)) {
    $user = new User();
    $user->username = $row['name'];
    $user->age = $row['age'];
    $data[] = $user;
}
$conn.close();
// Returns JSON data
echo json_encode($data);
Copy the code

So to verify that the data type returned is JSON, we just need to do the interfacetestCan. The blogger uses Chrome with a JSON plugin, so it’s easy to check. The diagram below:

JQuery & Ajax processing

JQuery is a really difficult functional library, so using JQuery to handle Ajax requests will reduce the complexity of writing code, and the underlying code will automatically handle compatibility issues. It’s a GEEK.

In this example, the purpose is to get the data in the data interface. So the code is simple as follows:

// Initialize two arrays to hold data retrieved from the database
    var names = [], ages = [];

    // Call Ajax to load data asynchronously
    function getusers(a) {
        $.ajax({
            type: "post",
            async: false,
            url: ".. /app/getuser.php",
            data: {},
            dataType: "json",
            success: function(result){
                if(result){
                    for(var i = 0 ; i < result.length; i++){
                        names.push(result[i].username);
                        ages.push(result[i].age);
                    }
                }
            },
            error: function(errmsg) {
                alert("Ajax error getting server data!"+ errmsg); }});return names, ages;
    }

    // Perform an asynchronous request
    getusers();Copy the code

ECharts end processing

Now everything is ready, the data is there, all that’s left is how to display it. Following the blogger’s building theory from the beginning, let’s put up the skeleton.

// Initialize the chart object
        var mychart = echarts.init(document.getElementById("container"));
        // Set the related items, which is called the scaffolding, to facilitate asynchronous ajax data filling later
        var option = {
            title : {
                text : 'Name and age distribution'
            },
            tooltip : {
                show : true
            },
            legend : {
                data : [ 'age' ]}, xAxis :[ {
                data : names
            } ], yAxis :[ {
                type : 'value'
            } ], series :[ {
                "name" : "age"."type" : "bar"."data" : ages
            } ]}; Mychart.setoption (option); // Assign the configuration item to chart object to display the related data.Copy the code

Note that xAxis: Names and Ages in series are the same data that JQuery used to retrieve using Ajax.

All front-end code

Personally feel that there is a complete code will give people a lot of inspiration, so here or post the front-end interaction code, but also convenient for everyone to view.


       
<html>
<head>
<meta charset="UTF-8">
<title>JQuery Ajax Test</title>
<script src=".. /static/js/echarts.js"></script>
<script src=".. / static/js/jquery - 1.11.1. Min. Js. ""></script>
</head>
<body>
    <h1>PHP Ajax ECahrts test</h1>
    <hr>
    <div id="container" style="width: 600px; height: 400px;"></div>
    <script>

    // Initialize two arrays to hold data retrieved from the database
    var names = [], ages = [];

    // Call Ajax to load data asynchronously
    function getusers(a) {
        $.ajax({
            type: "post",
            async: false,
            url: ".. /app/getuser.php",
            data: {},
            dataType: "json",
            success: function(result){
                if(result){
                    for(var i = 0 ; i < result.length; i++){
                        names.push(result[i].username);
                        ages.push(result[i].age);
                    }
                }
            },
            error: function(errmsg) {
                alert("Ajax error getting server data!"+ errmsg); }});return names, ages;
    }

    // Perform an asynchronous request
    getusers();


    // Initialize the chart object
        var mychart = echarts.init(document.getElementById("container"));
        // Set the related items, which is called the scaffolding, to facilitate asynchronous ajax data filling later
        var option = {
            title : {
                text : 'Name and age distribution'
            },
            tooltip : {
                show : true
            },
            legend : {
                data : [ 'age' ]
            },
            xAxis : [ {
                data : names
            } ],
            yAxis : [ {
                type : 'value'
            } ],
            series : [ {
                "name" : "age"."type" : "bar"."data" : ages
            } ]
        };

        // Assign the configuration item to chart object to display the relevant data
        mychart.setOption(option);




    </script>
<marquee>We're sure we can get here</marquee>

</body>
</html>Copy the code

Results,

At this point, the coding task is complete. So wait to see what happens.

So, modify the data a little bit and see what the result looks like after the refresh:

conclusion

Finally, let’s review the results of this experiment. In fact, it is a comparison of the “full stack” of ECharts (please allow me to use the unfortunate word O). Relatively simple implementation of the back-end and front-end data visualization display of a process.

Of course, the backend can be done not only by PHP, Java, Python, Golang, etc., but it is more convenient to use PHP. As long as you can get the data you want from this interface.