BottleでjQueryのPOSTアクションをうけとる
クソ雑魚なのでjQueryは避けていたのですが……
色々作るときに不便なのでやってみることにしました。
重いものを作る気はないので、Bottleと連携させます。
実際のところ
構成
$ tree
.
├── app.py
├── static
│ └── js
│ └── client.js
└── templates
└── base.jade
3 directories, 3 files
スクリプトの中身
app.py
from bottle import route, get, post, request, run, redirect, static_file, Bottle from bottle_jade import JadePlugin from os import path as op #初期化 app = Bottle() templates = op.dirname(op.abspath(__file__)) + '/templates/' jade = app.install(JadePlugin(template_folder=templates)) #静的ファイル置き場 @route('/static/:path#.+#', name='static') def static(path): return static_file(path, root='static') #ページ群本体 @get('/page') def topPage(): context = {"body": "basePage"} return jade.render('base.jade', **context) @post('/page') def postAction(): theText = request.params.get('message') if theText: messageString = "you posted: %s" % theText print(messageString) return messageString return "You didn't post anything." #アプリ起動 run(host='localhost', port=8080)
templates/base.jade
head
meta charset="utf-8"
title jQuerySample
script(src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js")
script(src="/static/js/client.js")
body
h2 #{body}
form(action="/page" method="post")
b please input blog contents. >>
input#ajaxTextbox(name="body" type"text")
input#ajaxButton(type="submit" value="Submit")
hr
p#ajaxP Nothing to see here.
static/js/client.js
$(document).ready(function() { $('form').submit(function(e) { var msg = document.getElementById('ajaxTextbox').value; $.ajax({ type: 'POST', url: '/page', data: "message=" + msg, success: function(response) { $('#ajaxP').html(msg); } }); e.preventDefault(); }); })
動かす
素はこんなページ

入力フォームに"44"と入れ投稿すると、"ajaxP"のidがついたトコが更新されます

コンソールにはこんな感じで出ます
you posted: 44 127.0.0.1 - - [19/Oct/2017 22:10:15] "POST /page HTTP/1.1" 200 14