Skip to main content
 首页 » 编程设计

jquery之如何在 Flask 中使用 Ajax

2025年02月15日30kuangbin

我正在可视化实时图表,就像这里的例子:Highcharts .基本上,它是对来自生成随机数据的 PHP 脚本 live-server-data.php 的数据的 Ajax 请求:

/** 
 * Request data from the server, add it to the graph and set a timeout  
 * to request again 
 */ 
function requestData() { 
    $.ajax({ 
        url: '/', 
        success: function(point) { 
            var series = chart.series[0], 
                shift = series.data.length > 20; // shift if the series is  
                                                 // longer than 20 
 
            // add the point 
            chart.series[0].addPoint(point, true, shift); 
 
            // call it again after one second 
            setTimeout(requestData, 1000);     
        }, 
        cache: false 
    }); 
} 
 
 
//---live-server-data.php 
<?php  
$x = time() * 1000;   
$y = rand(0, 100);    
$ret = array($x, $y); 
echo json_encode($ret); 
?> 

如何在 Flask 中做类似的事情,即从 Flask 请求随机生成的数字?

from flask import Flask, render_template, request, jsonify 
import random, datetime, json 
import time 
 
app = Flask(__name__) 
 
@app.route('/') 
def index(): 
 
    x = int(round(time.time() * 1000)) 
    y = random.randint(0, 100) 
    return json.dumps([x, y]) 
 
 
if __name__ == '__main__': 
    app.run(debug=True) 

请您参考如下方法:

在 Flask 中更简单:

@app.route('/') 
def index(): 
    x = datetime.timestamp(datetime.now()) * 1000 
    y = random.randint(0, 100) 
    return json.dumps([x, y]) 

但请注意,您必须在顶部添加以下导入才能使其正常工作:

import random, datetime, json 
from datetime import datetime