使用python和flask,如何将动态路由参数传递给AJAX请求调用的新路由?

时间:2019-01-22 22:31:51

标签: python jquery ajax flask

我已经在我的Python Flask应用中创建了动态路由,以显示动态html模板。在页面顶部,每个页面都有一个不同的图(wins_graph变量)。每个页面最初都会以应有的方式显示。

views.py(初始路线)

@app.route('/sports/nba/<team_abbr>-spending-performance/')
def nba_spending_performance_team(team_abbr):
    team_query = NBAWinsvsSalary.query.filter_by(team_abbr=team_abbr).order_by(NBAWinsvsSalary.season).all()
    team_colors = 'RdBu'
    wins_graph = Functions.wins_plot(team_query, 'No Seasons', 'rgba(175, 27, 50, 1)', team_colors)
    return render_template('sports/nba/spending-performance-team.html', wins_graph)

sports / nba / spending-performance-team.html

<header>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
</header>
<body>
    <div class="graph-container">
    <div class="graph-options">
    <label> Choose the plot type....</label>
        <span class="graph-options" id="atl_wins_graph">
            <button class="atl_wins_graph left selected" value="No Seasons">No Seasons</button>
            <button class="atl_wins_graph right" value="Seasons">Seasons</button>
        </span>
    </div>

    <div class="graph" id="wins_graph">
        <script>
            var graphs = {{wins_graph | safe}};
            Plotly.plot('wins_graph',graphs,{});
        </script>
    </div>
</div>
    <script src="{{ url_for('static', filename='js/jquery-3.3.1.js') }}"></script>
    <script src="{{ url_for('static', filename='js/plots.js') }}"></script>
</body>

如您所见,图形上方有两个按钮。我要显示第二个图形,但仅在单击第二个按钮时才显示。我已经写了一个AJAX调用来处理这个问题。

plots.js

$('.atl_wins_graph').on('click',function(){

$('#selected').html(this.value);
$('.atl_wins_graph').removeClass('selected');
$(this).addClass('selected');


    $.ajax({
        url: "/spending-wins/",
        type: "GET",
        contentType: 'application/json;charset=UTF-8',
        data: { 'selected': this.value },
        dataType:"json",
        success: function (data) {
            Plotly.newPlot('wins_graph', data );
        }
    });

});

以及与新图相对应的附加路线。

views.py(其他路线)

@app.route('/spending-wins/', methods=['GET', 'POST'])
def spending_change_wins():
    feature = request.args['selected']
    team_color = 'rgba(175, 27, 50, 1)'
    team_colors = 'RdBu'
    team_query = NBAWinsvsSalary.query.filter_by(team_abbr=team_abbr).order_by(NBAWinsvsSalary.season).all()
    graphJSON = wins_plot(team_query, feature, team_color, team_colors)
    return graphJSON

问题出在附加路由中,因为我尚未定义team_abbr。

我收到的错误是:

NameError: name 'team_abbr' is not defined

我了解为什么会收到此错误。如果我使用数据库中的实际值定义team_abbr,那么一切都会按照应有的方式工作。但这不是一个合理的解决方法,因为现在路线已经不动态了。

我只是想不知道如何在无需使用重定向的情况下将team_abbr参数从初始路由传递到其他路由。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

您可以将团队缩写存储为HTML5 data属性,并将缩写作为ajax data值的一部分传回:

views.py中,将团队缩写传递给模板:

@app.route('/sports/nba/<team_abbr>-spending-performance/')
def nba_spending_performance_team(team_abbr):
   team_query = NBAWinsvsSalary.query.filter_by(team_abbr=team_abbr).order_by(NBAWinsvsSalary.season).all()
   team_colors = 'RdBu'
   wins_graph = Functions.wins_plot(team_query, 'No Seasons', 'rgba(175, 27, 50, 1)', team_colors)
   return render_template('sports/nba/spending-performance-team.html', wins_graph, abbrev=team_abbr)   

spending-performance-team.html中,将abbrev的值呈现为每个按钮的data属性:

<span class="graph-options" id="atl_wins_graph">
   <button class="atl_wins_graph left selected" value="No Seasons" data-abbr="{{abbrev}}">No Seasons</button>
   <button class="atl_wins_graph right" value="Seasons" data-abbr="{{abbrev}}">Seasons</button>
</span>

现在,在plots.js中,更新data请求的ajax键:

$.ajax({
    url: "/spending-wins/",
    type: "GET",
    contentType: 'application/json;charset=UTF-8',
    data: { 'selected': this.value, 'abbr':$(this).data('abbr')},
    dataType:"json",
    success: function (data) {
        Plotly.newPlot('wins_graph', data );
    }
});

最后,在views.py中(其他路线):

@app.route('/spending-wins/', methods=['GET', 'POST'])
def spending_change_wins():
  feature = request.args['selected']
  team_color = 'rgba(175, 27, 50, 1)'
  team_colors = 'RdBu'
  team_query = NBAWinsvsSalary.query.filter_by(team_abbr=request.args.get('abbr')).order_by(NBAWinsvsSalary.season).all()
  graphJSON = wins_plot(team_query, feature, team_color, team_colors)
  return graphJSON

答案 1 :(得分:0)

sports/nba/spending-performance-team.html中创建一个值为team_abbr的隐藏输入,就像win_graphnba_spending_performance_team控制器中一样传递。然后让JS获得该值(类似$("#team-abbr").value)并将其作为ajax中的参数传递,然后就像选择您具有团队缩写一样。