request.form.get 返回 None 而不是 input

时间:2021-03-13 14:59:49

标签: javascript python html flask

我正在创建一个游戏,其中有人输入一个单词(产生搜索),您必须根据生成的结果猜测它是哪个单词。 它的工作原理是获取玩家 1 (input1) 输入的单词并将其与您的猜测 (input2) 进行比较。

当用户提交input1时,我的python代码获取并存储。 但是当第二个玩家输入 input2 并提交时, input1 被覆盖并且 request.form.get = None (虽然它得到 input2 完全没问题)。

发生了什么,我该如何解决?谢谢(PS:我知道这看起来像很多代码,但大部分都是为了上下文)

HMTL

<h4 id='playern' style='color:grey; margin:20px;'>Player 1</h4>


<!-- Search -->
<div id='cont1' style='display:flex; flex-direction:column; justify-content:center'>
    <p>Choose search for <em>Player 2</em> to guess.</p>
    <form id='form1' action='/multi' method='post'>
        <div class='form-group'>
            <input name='input1' id="input1" autofocus autocomplete='off' placeholder="cats, face..." type="text">
            <button id='input-btn' type='submit'>Submit</button>
            <hr>
        </div>
    </form>
</div>


<!--iframe-->
<div style='height:70%; width:100%; overflow:hidden;margin:10px 0px 50px 0px; position: sticky; display:flex; justify-content:center; border-style:none'>
    <iframe id='innerSpace' style="display:none;height:200%;width:60vw;margin-top:-120px;border-style:none;" title="Results"></iframe>
</div>


<!-- Guess -->
<div id='cont2' style='display:none; height: max-content; width:100%; position: sticky; border-style:none'>
    <h5>What is the search for these results?</h5>
    <form action='/multi' method='post'>
        <div class='form-group'>
            <input name='input2' id='input2' type='text'  autofocus autocomplete='off' placeholder='Guess'>
            <button id='guess-btn' type='submit'>Submit</button>
        </div>
    </form>
</div>

Javascript

<script>
  let is = document.getElementById('innerSpace');
  let input1 = document.getElementById('input1');
  let input2 = document.getElementById('input2');

  let playern = document.getElementById('playern');
  let cont1 = document.getElementById('cont1');
  let cont2 = document.getElementById('cont2');

  let spacer = document.getElementById('spacer');

  input1.addEventListener('change', searchFor);
  function searchFor() {
    //create constant variable with the value of input1
    const inp = input1;
    playern.innerHTML = 'Player 2';
    playern.style.marginTop = '0px';
    // hide first form and show the second one
    cont1.style.display = 'none';
    cont2.style.display = 'flex';
    cont2.style.flexDirection = 'column';
    cont2.style.justifyContent = 'center';
    cont2.style.alignItems = 'center';
    spacer.style.display ='none';
    is.style.display = 'flex';
    // search results
    let query = encodeURIComponent(input1.value);
    is.src = `https://search.givewater.com/serp?qc=images&q=weirdest+${query}`;
    // when user submits guess
    input2.addEventListener('change', function(){
        // trying to override None value by replacing with const value
        input1.value = inp.value;
        // tryin to re-submit input1
        document.getElementById("form1").submit();
    });
  }

蟒蛇

@app.route('/multi', methods =['POST', 'GET'])
@login_required
def multiplayer():

    #If user got here from link
    if request.method == 'GET':
        return render_template('multiplayer.html')

    #If user inputed something
    if request.method == 'POST':

        global inp
        inp = request.form.get('input1')

        #this stops the whole page from loading before user submits a guess
        while not request.form.get('input2'):
            #wait
            print('.', end='')
            time.sleep(1)
            #if guess exists
            if request.form.get('input2'):
                break

        ui = inp

        #Get guess
        guess = request.form.get('input2')

        #Get User id
        userId = session['user_id']

        #Get current score from user (and id)
        rows = db.execute('SELECT * FROM scores WHERE user_id = ?', userId)

        #if this user hasn't played yet
        ##add them to the table with a score of 0
        if not rows:
            db.execute('INSERT INTO scores (user_id, score) VALUES (?, ?)', userId, 0)
            rows = db.execute('SELECT * FROM scores WHERE user_id = ?', userId)

        #Get score of current user
        points = rows[0]['score']


        #If correct guess, increase points by 1
        if guess == inp:
            points += 1
            #Update score
            db.execute('UPDATE scores SET score = ? WHERE user_id = ?', points, userId )
            #copy to another variable
            w = inp
            g = guess
            s = points
            return render_template('results.html', title = 'Correct!', t1 = 'The search was', word = w, t2 = 'Your guess was', guess = g, score = s)
        #If wrong guess
        else:
            w = inp
            g = guess
            s = points
            return render_template('results.html', title = 'Incorrect', t1 = 'The search was', word = w, t2 = 'Your guess was', guess = g, score = s)

1 个答案:

答案 0 :(得分:0)

不要为 inpguess 使用全局变量,而是使用会话 cookie:

from flask import session

...

session['inp'] = request.form.get('input1')

...

session['guess'] = request.form.get('input2')

...

if session['inp'] == session['guess]:
   # do stuff

在全局变量中存储值不是你想要在这里做的事情;它的行为不像你想象的那样,也不是很实用。

相关问题