1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Flask + JavaScript (Confirm)との組み合わせについて

Posted at

本記事の背景

JavaScriptのConfirmはよく使われているが、Flaskとの組合わせで使う場合の記事がないように見えるため、本記事でまとめました。

本記事の基礎知識

  • Pythonの基本文法の理解
  • Flaskの基本的な動作の理解
  • JavaScriptの基本的な動作の理解

HTML側(Templates)

HTMLは以下を用意する

<!DOCTYPE html>
<html lang=“ja”>
  <head>
    <meta charset=“UTF-8“ />
    <title>confirm</title>
  </head>
  <body>
    <h1>確認内容</h1>
    <ul>
      <li>名前:{{ name }}</li>
      <li>コメント:{{ comment }}</li>
      <form action="/confirm_test" method="post"> 
        <input type="hidden" id="userInput" name="userInput"> 
        <button type="submit" name="free_button" value="free_button" onClick="confirmBooking('{{ name }}')"> registe </button> 
      </form>
      <script>
        function confirmBooking(elem) {
            if(confirm('do you want to registe this user?') == true) {
                alert("registed: " + elem); 
                document.getElementById("userInput").value = "True";
            }
            else { 
                 document.getElementById("userInput").value = "False";
                 return 0;
            }          
        }
    </script>
    </ul>
  </body>
</html>

Flaskのroutingは以下のように記述する

@app.route('/confirm_test', methods=['GET','POST'])
def confirm_test():
	name = 'yamada'
	comment = 'test comment'
	if request.method =="POST":
		userInput = request.form.get("userInput")
		if userInput == "True":
			print('registed this name')
		else:
			print('cancel this regist name')
	return render_template('confirm.html', name=name, comment=comment)

起動画面

image.png
登録ボタンを押下すると以下のようにポップアップダイアログが表示される
image.png

バックエンド側の処理

OK及びキャンセルボタンが押された場合はそれぞれ異なる処理が可能となる

127.0.0.1 - - [12/Jun/2023 19:27:42] "POST /confirm_test HTTP/1.1" 200 -
registed this name
127.0.0.1 - - [12/Jun/2023 19:27:46] "POST /confirm_test HTTP/1.1" 200 -
cancel this regist name

参考文献

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?