【问题标题】:FLASK unboundlocal error, while navigate through another pageFLASK unboundlocal 错误,同时浏览另一个页面
【发布时间】:2021-09-16 05:29:21
【问题描述】:

当我点击用户名时,它必须导航到包含特定用户信息的另一个页面。为了实现这一点,我尝试使用 jquery、python 和烧瓶。但我无法实现它,我收到以下错误。

谁能帮帮我。他们的代码有什么问题吗?

下面是代码

app.py

app.route("/ajaxfile",methods=["POST","GET"])
def ajaxfile():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
       userid = request.form['userid']
       cur.execute("SELECT * FROM user WHERE id = %s", [userid])
       result = cur.fetchall() 
    return render_template('detail.html', result=result)

index.html

 {% for row in emp %}    
  <tr>                
        <td>{{row.id}}</td>  
         <td><a data-id='{{row.id}}' class="userinfo btn btn-success" href="{{ url_for('ajaxfile') }}">{{row.name}}</a></td>  
  </tr>
  <script type='text/javascript'>
        $(document).ready(function(){
            $('.userinfo').click(function(){
                var userid= $(this).data('id');
                alert(userid)
                $.ajax({
                    url: '/ajaxfile',
                    type: 'post',
                    data: {userid: userid},
                    success: function(data){ 
                        
                    }
                });
            });
        });
</script>   

details.html

 {% for row in result %} 
 <table border='0' width='100%'>
 <tr>     
    <td style="padding:20px;">
    <p>Name : {{row.name}}</p>
    <p>Description : {{row.description}}</p>
    <p>Responsible person : {{row.responsibleperson}}</p>
    <p>Employee code : {{row.employeename}}</p>
    <p>Date : {{row.date_time}}</p>
    </td>
 </tr>
</table>       

【问题讨论】:

  • 您在if 范围内定义了结果变量,如果您发出发布请求,该变量将被执行。你在 render_template 函数中返回结果。如果没有发布请求,render_template 函数找不到任何变量 result 所以它给出错误
  • @charchit 可以为此提出解决方案。如果我删除一个 if 条件,我会得到 400 错误

标签: python html jquery mysql flask


【解决方案1】:

错误是不言自明的,您在定义之前使用了变量 result 。

您正在发出 ajax 请求以将数据发送到烧瓶。如果返回 if 范围内的任何数据,则将其存储在 js 中 success 函数的 data 参数中。

你不能那样render_template,你有两个选择

  1. 您应该使用表单发送数据,之后您可以在 if 范围内使用return render_template() 函数。但是如果没有来自 index.html 的发布请求,您将无法访问详细信息页面
  2. 您可以使用 ajax 发送数据并在 if 范围内返回结果变量。return jsonify{"res":result},现在data 具有 json 并且data.ressuccess 函数中具有result 的值。您可以在同一页面上使用 javascript 的 for 循环和使用 jquery 的 append 数据。 制作一个 td 标签,给它 Id 并在 jquery 中使用它。

如果你提供完整的代码,我可以编辑它并发送或张贴在这里。通过 github 或 discord。

编辑:你可以这样做。

from flask import jsonify 
app.route("/ajaxfile",methods=["POST","GET"])
def ajaxfile():
    cur = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    if request.method == 'POST':
       userid = request.form['userid']
       cur.execute("SELECT * FROM user WHERE id = %s", [userid])
       result = cur.fetchall()
       return jsonify{result=result}
    return "Hello world" # to avoid error, you can also allow only post methods by removing get from methods.

在 html 中:您必须在 index.html 文件中执行此操作。

[...] 
<table border='0' width='100%'>
 <tr>     
    <td style="padding:20px;" id="my_td">
    
    </td>
 </tr>
</table> 

js:在成功函数中。

 success: function(data){ 
   for (row of data.result){
   $("#my_td").append(`<p>Name : row.name</p><p>Description : row.description</p><p>Responsible person : row.responsibleperson</p><p>Employee code : row.employeename</p><p>Date : row.date_time</p>`)                           
      }
 }

方法二使用表单

Html : 创建一个表单标签和一个隐藏输入,其值为 row.id

{% for row in emp %}    
<tr>
     <form action="/ajaxfile" method="POST">
          <input value="{{row.id}}" type="hidden" name="userid">
       <td>{{row.id}}</td>
     <td><button data-id='{{row.id}}' type="submit" class="userinfo btn btn-success" >{{row.name}}</button></td>
     </form>
</tr>
{% endfor %}

Python:保持一切不变并在 if 范围内返回 render_template。

[...]
if request.method == 'POST':
     [...]
     return render_template('detail.html', result=result)

【讨论】:

  • 我已经发布了与这个问题相关的所有代码。仍然如果你想要代码,请告诉我我必须如何与你分享代码?我仍然无法从上面的答案中解决它。如果你写它对我会有帮助。因为我对 jquery 和 ajax 不太熟悉
  • @ShwethaK 您可以通过 discord charchit#8198 与我联系,或者您可以创建一个 github 存储库并与我分享它的链接。
  • @ShwethaK 我更新了答案,不要制作新的 html 文件,而是在 index.html 中添加上面的 sn-p。如果你想创建一个新文件,那么我可以告诉你表单的另一种方法。
  • 我想用用户信息的所有信息制作新的html文件为detail.html。
猜你喜欢
  • 2015-08-01
  • 1970-01-01
  • 2019-10-25
  • 1970-01-01
  • 1970-01-01
  • 2013-11-12
  • 2021-06-18
  • 2013-07-11
  • 1970-01-01
相关资源
最近更新 更多