Read data based on the Echarts+ajax database and return to the front end

Source: Internet
Author: User
Tags json min prepare

1.echarts of the official online demo, are directly written dead random data, there is no interaction with the database, so I wrote a bit, OK, we start step by step through the whole process.

On the website of the simplest of the small demo to make changes it. The results of the small demo on the Internet are as follows: (very familiar, there is no)


2. Create a new echarts.html file by using the Echarts method. Prepare a DOM with the size (width and height) for the echarts (speak a little bit, familiar friends skip directly)


<! DOCTYPE html><meta charset= "Utf-8" >
<title>ECharts</title><!--prepare a DOM--> with size (width and height) for echarts
<div id= "main" style= "height:400px" ></div></body>

New <script> tags introduced to AMD Spec-compliant loaders, such as Esl.js, introduced jquery to prepare for an AJAX send POST request


<script src= "Echarts/esl.js" ></script>
<script src= "Echarts/jquery.min.js" ></script>

Path configuration

Path configuration
Require.config ({
paths:{
' Echarts ': ' Echarts/echarts ',
' Echarts/chart/bar ': ' Echarts/echarts '
}
});

The last is used: The following code is the official web, the red part of the data and so we modify the read from the database




Use


Require


[


' Echarts ',


' Echarts/chart/bar '//loading bar module with column graph, loading on demand


],


Function (EC) {


Initializes the Echarts&lt;a href= "Http://www.suchso.com/catalog.asp?tags=ECharts%E6%95%99%E7%A8%8B" class= based on the prepared DOM Keylink "title=" chart target= "_blank" &gt; Chart &lt;/a&gt;


var MyChart = ec.init (document.getElementById (' main '));





var option = {


ToolTip: {


Show:true


},


Legend: {data:[' sales ']


},


Xaxis: [


{type: ' Category ', data: ["shirts", "sweaters", "chiffon shirts", "trousers", "heels", "socks"]


}


],


YAxis: [


{type: ' value '


}


],


Series: [


{


"Name": "Sales",


"Type": "Bar", "Data": [5, 20, 40, 10, 10, 20]


}


]


};





Loading data for a Echarts object


mychart.setoption (option);


}


);


The code for the entire previous page is as follows: The main thing is to modify the data in option Xaxis and series, these 2 data in the official website of the demo are directly written dead, here we use Ajax to send a POST request:




&lt;! DOCTYPE html&gt;&lt;head&gt;


&lt;meta charset= "Utf-8" &gt;


&lt;title&gt;ECharts&lt;/title&gt;


&lt;!--from Baidu CDN--&gt;


&lt;script src= "Echarts/esl.js" &gt;&lt;/script&gt;


&lt;script src= "Echarts/jquery.min.js" &gt;&lt;/script&gt;&lt;/head&gt;&lt;body&gt;


&lt;!--prepare a DOM--&gt; with size (width and height) for echarts


&lt;div id= "main" style= "height:400px" &gt;&lt;/div&gt;


&lt;script type= "Text/javascript" &gt;


Path Configuration Require.config ({


paths:{


' Echarts ': ' Echarts/echarts ', ' echarts/chart/bar ': ' Echarts/echarts '


}


}); Using Require (


[' Echarts ', ' echarts/chart/bar '//using a histogram to load bar modules, loading on demand]


Drewecharts


); function Drewecharts (EC) {//Based on prepared DOM, initialize echarts chart MyChart = Ec.init (document.getelementby Id (' main '));


var option = {


ToolTip: {


Show:true


},


Legend: {data:[' sales ']


},


Xaxis: [


{


Type: ' Category ',


Data: (function () {var arr=[];


$.ajax ({type: Post),


Async:false,//Synchronous execution URL: "Bar.do", Data: {},


&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; dataType: "JSON",//return data in the form of json&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; success:function (Result) {&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (Result) {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;& nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (Var i=0;i&lt;result.length;i++) {


Console.log (Result[i].name);


Arr.push (Result[i].name);


}


}





},


Error:function (errormsg) {


Alert ("Sorry, Grandpa, the chart request data failed!");


Mychart.hideloading ();


}


}) return arr;


})()


}


],


YAxis: [


{type: ' value '


}


],


Series: [


{"Name": "Sales", "type": "Bar", "Data":(func tion () {var arr=[];


$.ajax ({type: Post),


Async:false,//Synchronous execution URL: "Bar.do", Data: {},


&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; dataType: "JSON",//return data in the form of json&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; success:function (Result) {&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (Result) {&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;& nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (Var i=0;i&lt;result.length;i++) {


Console.log (Result[i].num);


Arr.push (Result[i].num);


}


}


},


Error:function (errormsg) {


Alert ("Sorry, Grandpa, the chart request data failed!");


Mychart.hideloading ();


}


}) return arr;


})()





}


]


};


Loads the data mychart.setoption for the Echarts object (option);


} &lt;/script&gt;&lt;/body&gt;


3. The path to the Ajax POST request in the previous step is the URL: "Bar.do" configures the following map in Web.xml as follows:

<servlet>
<servlet-name>helloBar</servlet-name>
<servlet-class>com.helloBar</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloBar</servlet-name>
<url-pattern>/bar.do</url-pattern>
</servlet-mapping>
Such By Bar.do, you will find the HelloBar servlet below the COM package. The main role of this servlet is to read data to the database and return to the previous section of the page, where I use a local data source to link, about the local data source how to even here I do not tell, will not students can be found in my blog. Of course, you can also use the most basic JDBC to connect.

public void DoPost (HttpServletRequest request, httpservletresponse response)


Throws Servletexception, IOException {


A Bardao object was created, Bardao primarily to connect to the database and manipulate the database


Bardao bardao=new Bardao ();


Call Bardao's Select_all () method to fetch all the data from the database is a arraylist,arraylist inside is a Barbean


arraylist&lt;barbean&gt; array = Bardao.select_all ();


Set the encoding format when returning


Response.setcontenttype ("text/html; Charset=utf-8 ");


Call the Jsonarray.fromobject method to convert an object in an array to a JSON-formatted array


Jsonarray Json=jsonarray.fromobject (array);


System.out.println (Json.tostring ());


Return to previous paragraph page


PrintWriter out = Response.getwriter ();


OUT.PRINTLN (JSON);


Out.flush ();


Out.close ();


}


The bar table format for the database is shown below:


Code for Barbean:

Import java.io.Serializable;


Import Java.sql.Date;


public class Barbean {


private String name;


private int num;


Public String GetName () {


return name;


}


public void SetName (String name) {


THIS.name = name;


}


public int Getnum () {


return num;


}


public void setnum (int num) {


This.num = num;


}





}


Code for Bardao:


public class Bardao {


private static InitialContext context = NULL;


Private DataSource DataSource = null;


private static final String Select_all = "Select*from bar";


Public Bardao () {


try{


if (context = = null) {


context = new InitialContext ();


} DataSource = (DataSource) context.lookup ("Java:comp/env/jdbc/sampleds");


}catch (namingexception E2) {





}


}


Public Connection getconnection () {


Connection conn = null;


try{


conn = Datasource.getconnection ();


}catch (SQLException e) {}


Return conn;


}


Public arraylist&lt;barbean&gt; Select_all ()


{


Connection conn = null;


PreparedStatement pstmt = null;


ResultSet rst = null;


try{


conn = Datasource.getconnection ();


pstmt = Conn.preparestatement (Select_all);


rst = Pstmt.executequery ();


arraylist&lt;barbean&gt; array = new arraylist&lt;barbean&gt; ();


while (Rst.next ())


{


Barbean bar = new Barbean ();


Bar.setname (rst.getstring ("name"));


Bar.setnum (rst.getint ("num"));


Array.add (bar);


}


Pstmt.close ();


Rst.close ();


return array;


}catch (SQLException e) {


System.out.println ("Error occured at Bardao-&gt;select_all ()");


return new arraylist&lt;barbean&gt; ();


}finally{


try{


Conn.close ();


}catch (SQLException e) {


System.out.println ("Error occured at closing connection in Bardao");


}


}


}


}

4. The page in the previous paragraph reads the contents of the returned array after confirming the AJAX request success. You can show it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.