Javascript 如何在flask上的同一页面中显示多个html?

Javascript 如何在flask上的同一页面中显示多个html?,javascript,jquery,html,flask,Javascript,Jquery,Html,Flask,我正在尝试创建一个应用程序,在这个应用程序中,我可以单击一列中显示的页面中的链接/按钮,并在另一列中显示html,而无需重新加载页面。我也在尝试这样做,我可以有多个链接/按钮,如果我点击一个不同的链接,它会改变显示 到目前为止,我是通过在plot html上重新绘制整个页面来实现的,但是速度很慢。我的html视图是这样的 <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/

我正在尝试创建一个应用程序,在这个应用程序中,我可以单击一列中显示的页面中的链接/按钮,并在另一列中显示html,而无需重新加载页面。我也在尝试这样做,我可以有多个链接/按钮,如果我点击一个不同的链接,它会改变显示

到目前为止,我是通过在plot html上重新绘制整个页面来实现的,但是速度很慢。我的html视图是这样的

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!--// JQuery Reference, If you have added jQuery reference in your master page then ignore, 
// else include this too with the below reference
-->

<script src="https://cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.4/css/jquery.dataTables.min.css">
<link href="static/style.css">

<script type="text/javascript">
    $(document).ready(function () {
        $('#table_id').dataTable();
    });
</script>



</head>
<body>

  <div class="column" style="background-color:#aaa;">

    <table id="table_id" 

    class="">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th> 
        <th>Age</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td> <a href="javascript:plot1('par1', 'par2', 'par3');">Jill </a></td>
        <td>Smith</td> 
        <td>50</td>
      </tr>
      <tr>
        <td><a href="javascript:plot2('par1', 'par2', 'par3');">Eve </a</td>
        <td>Jackson</td> 
        <td>94</td>
      </tr>
    </tbody>
    </table>

    <script type="text/javascript">
        $(document).ready(function () {
        $('#table_id').dataTable();
        });
    </script>

  </div>
  <div class="column2" style="background-color:#bbb;" id="targetColumn1">
    <script>
    function plot1(par1, par2, par3) {
        var arr = ['/plot1?par1=', par1, '&par2=', par2, '&par3=',  par3];
        var urlcpar = arr.join('');
        $.ajax({
          type: "GET",
          url: urlcpar,
          success: function(response) {
               $("#targetColumn1").html(response);
          },
         });
    }
    </script>


  </div>
  <div class="column3" style="background-color:#bbb;" id="targetColumn2" >
    <script>
    function plot2(par1, par2, par3) {
        var arr = ['/plot2?par1=', par1, '&par2=', par2, '&par3=',  par3];
        var urlcpar = arr.join('');
        $.ajax({
          type: "GET",
          url: urlcpar,
          success: function(response) {
               $("#targetColumn2").html(response);
          },
          error: function(xhr) {
              //Do Something to handle error
          }
         });
    }
    </script>



  </div>

</body>
</html>
我的绘图HTML2看起来像

<style>
* {
    box-sizing: border-box;
}

body {
    margin: 0;
}
.column {
    float: left;
    width: 100.0%;
    padding: 10px;
    height: 50.0%; /* Should be removed. Only for demonstration */
}


/* Create three equal columns that floats next to each other */
.column2 {
    float: left;
    width: 50.0%;
    padding: 10px;
    height: 50.0%; /* Should be removed. Only for demonstration */
}

/* Create three equal columns that floats next to each other */
.column3 {
    float: right;
    width: 50.0%;
    padding: 10px;
    height: 50.0%; /* Should be removed. Only for demonstration */
}



/* Clear floats after the columns */
.row:after {
    content: "";
    display: table;
    clear: both;
}

/* Responsive layout - makes the two columns stack on top of each other instead of next to each other */
@media (max-width: 600px) {
    .column {
        width: 100%;
    }
}
</style>
{{ plot|safe }}
我的应用程序是这样的,我有两个html,我想在同一个页面上显示

from flask import * 
import os
import matplotlib.pyplot as plt
import numpy as np

app = Flask(__name__)

app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True

# IF CHANGE THE ROUTE HERE FOR '/<eventid>' works 
@app.route('/view/<eventid>')
def page_view(eventid):
    global event
    event = eventid
    print(event)
    return render_template('view.html')

@app.route("/plot1")
def plot1():
    par1 = str(request.args.get('par1'))
    par2 = str(request.args.get('par2'))
    par3 = str(request.args.get('par3'))

    fname = './static/'+event
    if not os.path.exists(fname):
        os.mkdir(fname)

    f = open(fname+'/example.html', 'w+')
    f.write('<HTML><p> \
            <body>' \
          +par1+par2+par3+'</p> \
          <img src="./plot/test.png"> \
          </body> </HTML>')
    f.close() 

    #fl = fname+'/example.html'
    #fl = 'http://visjs.org/examples/network/nodeStyles/images.html' 
    fl = fname+'/Network _ Images.html'
    return render_template('plot1.html', html='<object width="100%" height="100%" data=\"'+fl+'\"></object>')


@app.route("/plot2")
def plot2():
    par1 = str(request.args.get('par1'))
    par2 = str(request.args.get('par2'))
    par3 = str(request.args.get('par3'))

    fname = './static/'+event
    if not os.path.exists(fname):
        os.mkdir(fname)

    fname = fname+'/plot/' 
    if not os.path.exists(fname):
        os.mkdir(fname)

    t = np.arange(0.0, 2.0, 0.01)
    s = np.sin(2*np.pi*t)
    plt.plot(t, s)

    plt.xlabel('time (s)')
    plt.ylabel('voltage (mV)')
    plt.title('About as simple as it gets, folks')
    plt.grid(True)
    plt.savefig(fname+"/test.png")

    fl = fname+'/test.png'
    return render_template('plot2.html', plot='<img src=\"'+fl+'\">')


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

任何帮助都将不胜感激。

您可以使用AJAX从服务器获取内容,并在第二列中显示该内容。下面是说明此概念的示例应用程序:

app.py

模板/view.html

模板/plot.html


答案并不简短,我不能仅用您提供的部分代码就完全完成它,但我可以给您一些指导,以便您可以继续

将/PLOT路由更改为返回json而不是渲染模板

@app.route('/plot')
def plot():
    ...
    return flask.jsonify(jsongraph)
然后,您需要将所有需要的库添加到第一个html中,因此包括plotly js。之后,您需要添加ajax调用,而不是按钮的链接:

<div class="column" style="background-color:#aaa;">
    <span id="link">link text</span>
</div>
<div class="column" style="background-color:#bbb;" id="target">
    <!-- DISPLAY SOMETHING HERE -->
</div>
并在jQuery中添加类似示例的内容

<script>
$(document).ready(function(){
   $.get('/ploty', function(data){
       ...
       Plotly.plot(..., graph.data, graph.layout);
       ...
   });
});
</script>

Idk plotly是如何准确工作的,但您需要以某种方式向其提供目标div的id。另外,您可能需要清除div之前的内容。

只是一个粗略的猜测。。。如果您试图在一页上绘制多个绘图,并且希望它们以某种方式相互连接,那么您可能需要查看一下,这也是构建在flask顶部的。这是一个你考虑过使用框架吗?我想过,但我看到html5不再支持它了,是吗?嗨@Matt,我想你的答案正是我想要的。我使用href='javascript:showColumpar1,…,parN',然后在一个类似的ajax调用中将url格式化为plot?par1=x&…&parN=xN,但是当我执行$targetColumn.htmldata调用时,我生成了一个png及其html,但它返回了一个url视图/什么,我不明白为什么。如果我用您的id方法替换href:javascript:我如何使用参数?当您说它返回url视图/什么东西时,您的确切意思是什么?当我在终端上检查flask的打印信息时,我可以看到调用的格式正确,如我可以看到/plot?par1=x。。。然后我还看到GET/view/static/data HTTP/1.1 404,在浏览器中我还看到没有找到资源。我现在将我的应用程序分成几部分,创建一个可复制的小示例,看看错误在哪里。我想说,请求来自你的plotly代码中的某个地方,如果没有看到代码,很难说。
Plot with args: <br /><br/ >

<ul>
    {% for a in request.args %}
        <li>{{ a }} - {{ request.args[a] }}</li>
    {% endfor %}
</ul>
@app.route('/plot')
def plot():
    ...
    return flask.jsonify(jsongraph)
<div class="column" style="background-color:#aaa;">
    <span id="link">link text</span>
</div>
<div class="column" style="background-color:#bbb;" id="target">
    <!-- DISPLAY SOMETHING HERE -->
</div>
<script>
$(document).ready(function(){
   $.get('/ploty', function(data){
       ...
       Plotly.plot(..., graph.data, graph.layout);
       ...
   });
});
</script>