首页 > 解决方案 > 将 JSON 数据从 Python 发送到 Javascript 并访问它们。

问题描述

我有一个 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 中并将它们用作图表数据。

我是 Javascript 和 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"  }
            ]
        }
        ]
    });

谢谢

标签: javascriptpythonjsonajaxcanvasjs

解决方案


因此,让我快速概述一下 AJAX 和烧瓶如何协同工作。

假设您有一些从数据库中获得的数据,就像这样

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)

推荐阅读