2016-09-29 49 views
1

我正在嘗試製作一個網絡應用程序,就像一個微型推文。帖子從數據庫中提取出來,我想爲每個帖子設置一個「投票」按鈕,如下圖所示。有很多按鈕和數據庫更新的瓶子

posts

每個帖子都有一個idauthorbodylikes財產。當點擊投票表決時,likes屬性需要更新。

我的問題是如何確定哪個按鈕被點擊。在這種情況下,對於route()函數和html模板,什麼是一個好的策略?

我正在考慮爲每個按鈕添加一個名稱,並在名稱中加上post.id,然後檢查是否有request。但帖子的數量在手前不得而知,應該怎麼寫request檢查route()函數?

我現在的模板是如下

<table class="table table-striped"> 
{% for post in posts %} 
<tr> 
<td> {{ post.id }} </td>             
<td> <img src="{{ post.author.avatar(50) }}"> </td>       
<td> <b>{{ post.body }}</b> </td>                        
<td> <button type="button" name='{{'up.'+ post.id|string}}' class="btn btn-default"> 
<span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span> 
</button> 
{{ post.likes}} </td> 
</tr> 
{% endfor %} 
</table> 

和當前route()是這樣

@bbs.route('/', methods=['GET', 'POST'])         
def index():                
    posts = Post.query.all()            
    return render_template('bbs/index.html', posts=posts) 

回答

1

一個乾淨的方式做到這一點是添加一個數據屬性,在你button標籤和每個upvote/downvote做一個ajax請求。

https://developer.mozilla.org/en/docs/Web/Guide/HTML/Using_data_attributes

在你的情況下,它會被稱爲data-id

在JavaScript

然後,單擊該按鈕時,得到這個數據的屬性值,並且手藝您的網址爲這樣:

/upvote/<data-id> 

,並使用AJAX GET請求調用它(這樣的頁面不刷新)。

現在在燒瓶側得到ID爲這樣:

@app.route('/upvote/<post_id>') 
def upvote(post_id): 
    print('%s upvoted' % post_id) 
    # do your db update here and return a json encoded object 

,然後在JavaScript方面再次,當你從瓶中你的答案,相應地更新您的按鈕。

假設你把其他類在給予好評按鈕例如:upvote_button你使用jQuery,您的JavaScript可能看起來像:

<script type='text/javascript'> 
$('.upvote_button').click(function(ev){ 
    var id = $(ev.currentTarget).attr('data-id'); 
    $.get("/upvote/" + id, function(data) { 
     // change your button here, and remove its upvote_button class 
     alert(data); 
    }); 
}); 
</script> 
+0

感謝您的答覆。由於缺乏JavaScript知識,我仍然在爲此苦苦掙扎。在我的'upvote'路由函數中,我'返回json.dumps({'likes':post.likes})''。在JavaScript中,'alert(data)'似乎顯示正確的字典,但是當我使用'data.likes'時,它給出了'undefined'。我做錯了什麼? – nos

+0

嘗試:'data ['likes']' –