将JSON数据从Python发送到Javascript并进行访问。

时间:2018-09-24 17:40:50

标签: javascript python json ajax canvasjs

我有一个python文件,该文件从数据库中获取数据并以JSON的形式返回。

import pymysql;
import json;
from flask import Flask, render_template, request, redirect, Response
app = Flask(__name__)

@app.route('/test', methods=["POST", "GET"])
def getMySQlData():
    tableData = []
    connection = pymysql.connect(host='db-auto-performancetesting',
                                 user='DBUser',
                                 password='*******',
                                 database='DbPerformanceTesting',
                                 port=3302,
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)

    try:
        with connection.cursor() as cursor:
            sql = "SELECT TestcaseName, AverageExecutionTimeInSeconds FROM PASPerformanceData WHERE BuildVersion='38.1a141'"
            cursor.execute(sql)
            while True:
                row = cursor.fetchone()
                if row == None:
                    break
                tableData.append(row)
            tableDataInJson =  json.dumps(tableData, indent=2)
            print tableDataInJson
            return tableDataInJson
    finally:
        connection.close()

if __name__ == "__main__":
    app.run()

在将这些JSON数据收集到HTML和Javascript并将其用作图表数据时,我需要帮助。

我是Java和Ajax的新手。有人可以帮我从Javascript编写对python文件的ajax调用并检索返回的JSON数据。

<!DOCTYPE HTML>
<html style="height:100%;">
<head>
<style type="text/css">
body {
    overflow:hidden;
}
</style>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript">

window.onload = function () {
    var chart1 = new CanvasJS.Chart("chartContainer1", {
        title:{
            text: "Launch Application"              
        },
        axisY:{
        title: "Average Execution Time(seconds)"
        },
        axisX:{
        title: "Software Version",
        labelAngle: 180
        },
        data: [              
        {
            // Change type to "doughnut", "line", "splineArea", etc.
            indexLabelFontSize: 16,
            labelFontSize: 16,
            type: "column",
            dataPoints: [
                { label: "ReleaseVersion \n (20.1a121)",  y: "**Data recieved from JSON, indexLabel**": "6.0 s" },
                { label: "PreviousVersion \n (38.1a140)", y: "**Data recieved from JSON**", indexLabel: "5.0 s"  },
                { label: "CurrentVersion \n (38.1a.141)", y: "**Data recieved from JSON**", indexLabel: "5.4 s"  }
            ]
        }
        ]
    });

谢谢

1 个答案:

答案 0 :(得分:1)

因此,让我快速概述一下AJAX和flask如何一起工作。

假设您有一些从数据库中获得的数据

items=[{"id":123,"name":"abc","lastname":"xyz"}]

您可以用一小段代码存储类似的内容

result = cursor.fetchall()
links = []
num = 0
for item in result:
    if links.__len__()-1 != num:
        links.append({})
    links[num]['id'] = item[0]
    links[num]['name'] = item[1]
    links[num]['lastname'] = item[2]
    #links.append({}) extra append should be created
    num += 1

现在有趣的AJAX部分

让我们说您有一个想要提交的简单表格。

    <form id="searchForm" action="/" method="POST">
    <input type="text" id="search" name="search" placeholder="Search">
    <input type="submit" value="Search">
    </form>

要停止默认的提交操作,您可以使用一个类似这样的脚本

$(document).ready(function() {
//#addLinkForm is nothing but the id of the form (works well if you have multiple forms in your page)
    $('#addLinkForm').on('submit',function(event){
//This is where the data is sent
    $.ajax({
        url: '/adminAJAX',
        type: 'POST',
        data: $('#addLink'),
    })
//this is done when the response is received
    .done(function(data) {
        console.log("success " + data);
    });

    event.preventDefault();
});
});

响应将在您的浏览器控制台中。您可以根据需要使用收到的数据

要使其正常工作,您还需要

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

在您的HTML代码中

最后一件事。为了使所有这些正常工作,您还需要服务器端,我想这将是您的最佳选择

@app.route('/adminAJAX',methods=['POST'])
def adminAJAX():
#your processing logic
 items=[{"id":123,"name":"abc","lastname":"xyz"}] #just an example
 return json.dumps(items)