2016-11-24 30 views
0

我正在用Bottle創建一個小瑣事遊戲,並且遇到了一些麻煩。 頁面加載時,隨機瑣事問題從數據庫中提取並出現在瀏覽器中,當頁面首次加載時,服務器會自動嘗試從表單輸入中獲取值,並且輸入爲空(在那裏沒有什麼意外)。但是,如果我試圖在輸入字段中輸入瑣碎問題的答案,然後單擊提交按鈕,頁面將重新加載,並從數據庫中獲取下一個瑣事問題。我的用戶輸入從不匹配當前的瑣事問題,因爲它始終保持上一個問題的價值。在進行新的數據庫查詢之前評估用戶輸入

如何從特定數據庫查詢的用戶輸入中獲取值,而無需在提交頁面時重新加載並生成新的隨機查詢?

在我game.py文件:

@app.route("/game", method=["POST"]) 
def game(db): 
    db.execute("select * from questions order by rand() limit 1") 
    data = db.fetchall() 
    guess = "" 
    name = "" 
    for d in data: 
     country_name = d["name"] 

    if request.POST.the_guess: 
     guess = request.POST.the_guess.strip() 

return bottle.template("temp", data=data) 

在我temp.tpl

<form method="POST" action="/game"> <input type="text" name="the_guess"> <input type="submit" value="guess"> </form>

+0

您應該將問題ID放入表單中的隱藏輸入中,然後從'request.POST'中獲取猜測和ID,然後執行數據庫查詢以查看答案 – Barmar

+0

我注意到當我提交表單時,它清除了存儲在我的服務器文件中的所有值,我不是這樣。 –

+0

你的意思是刪除數據庫表中的所有內容嗎? – Barmar

回答

1

您的要求視做用戶是否不提交表單,即同樣的事情

  • 獲取隨機問題
  • strip如果提供了響應。

但是,你必須要考慮兩種情況

  • 用戶點擊玩遊戲的鏈接「開始」上,因此剛剛登陸頁面上。
  • 用戶提交表單,你必須評估他reposne

要做到這一點,你必須通過的問題ID作爲隱藏字段,所以你知道什麼是正確的響應。基於對user_feedback

@app.route("/game", method=["POST", "GET"]) 
def game(db): 
    # Store if user answered last question correctly or not 
    user_feedback = None 
    # See if this view is beng invoked by user submitting an answer 
    if "submit" in request.POST: 
     guess = request.POST.the_guess.strip() 
     qid = request.POST.qid 
     # Lookup DB for answer of question with ID qid. Store it as answer 
     if guess == answer: 
      user_feedback = True 
     else: 
      user_feedback = False 
    # This part will always execute 
    db.execute("select * from questions order by rand() limit 1") 
    data = db.fetchall() 
    for d in data: 
     country_name = d["name"]   
    return bottle.template("temp", data=data, user_feedback=user_feedback) 

:因此

<form method="POST" action="/game"> 
    <input type="text" name="the_guess"> 
    <input type="submit" value="guess"> 
    <input type="hidden" name="qid" value="YOUR_QUESTION_ID"> 
</form> 

視圖代碼必須做這樣的事情(我不知道瓶子視圖的語義正確,所以認爲這是僞代碼) ,在你的模板中你可以顯示一個「正確!」或「錯誤:」消息