1. 程式人生 > 其它 >python/flask 從後臺接收資料,展示在前端

python/flask 從後臺接收資料,展示在前端

1.app.py檔案裡的路由

 1 #獲取mysql裡面的資料,展示在個人使用者介面
 2 @app.route('/personal_info', methods=['GET', 'POST'])
 3 def personal_info():
 4 # 獲取登入路由定義的user值
 5 user = session.get('user')
 6 
 7 # 連線資料庫
 8 conn = pymysql.connect(host='192.168.0.6', user='root', password='123', db='database1', charset='utf8')
 9 
10
# 拿到遊標 11 cursor = conn.cursor() 12 13 # 執行sql語句 14 sql = 'SELECT * FROM userinfo where username="%s"' % (str(user)) 15 cursor.execute(sql) 16 u = cursor.fetchall() 17 18 # 資料庫和遊標關閉 19 cursor.close() 20 conn.close() 21 22 #如果沒有登入,就獲取不到最上面那個user,就不會執行上面的sql語句,u就沒有得到值 23 #如果u沒有值的話,就賦給u一個元組型別(和資料庫中一樣)的值,其中id只是佔了一個位置(資料庫第一列是id,不輸出)
24 if not u : 25 u = ((id,"未登入,請登入",),) 26 27 return render_template('personal_info.html', u=u)

2.個人資訊(前端)介面

<div class="">
            #form表單的地址填寫app.py裡面的路由
            <form action="/personal_info" class="">
                <table>
                    這是一個for迴圈,和下面的endfor配套使用,固定格式,輸出u中的值
                    {% for i in u %}
                    
<tr> <td>使用者名稱:</td> #這裡定義一個id是為了下面寫js,把一個超連結(HTML的語句)展現在使用者名稱這個表格裡面 <td id="is_login">{{ i[1] }}</td> </tr> <tr> <td>性別:</td> <td>{{ i[5] }}</td> </tr> <tr> <td>出生日期:</td> <td>{{ i[6] }}</td> </tr> <tr> <td>郵箱:</td> <td>{{ i[3] }}</td> </tr> <tr> <td>聯絡方式:</td> <td>{{ i[4] }}</td> </tr> {% endfor %} </table> </form> </div> #js,把一個超連結(HTML的語句)展現在使用者名稱這個表格裡面 <script> #定義一個變數a接收該id空格的內容,就是{{ i[1] }} a = document.getElementById("is_login").innerHTML // console.log("a=" + a) if(a=="未登入,請登入") { document.getElementById("is_login").innerHTML = "未登入,請<a href='login.html' target='_blank'>登入</a>"} </script>

3.在其他網頁點選個人資訊按鈕,跳轉到個人資訊頁面

#一個例子:本來data-url="personal_info.html",但是這裡要登入上面的路由名稱
<li class="layui-nav-item">
                <a href="javascript:;" data-url="/personal_info" data-id="16" data-text="個人資訊"><i class="iconfont">&#xe606;</i>個人資訊</a>
              </li>

結束,參考文章https://blog.csdn.net/vitaair/article/details/80220598