pythonでajaxの練習 2012/05/312012/05/31 Takeshi いやぁ、おもしろいなぁ(今更)。 リクエストボディをそのまま返すような python スクリプトを作って、画面遷移なしで結果表示するようなのを作ってみました。 python 以外には bottle が必要です。(sudo yum install python-bottle) なんで、jQuery.ajax() を使わずに XMLHttpRequest をいちいち組み立てているかというと、multipart/form-data の扱いに難があったためです。 # vim: ts=4 sw=4 fenc=utf-8 import bottle @bottle.get('<file:re:^.*\.(css|less|js|jpg|png|gif|ttf)>') def static_file(file): return bottle.static_file(file, root='./web') @bottle.get('/') def index(): return '''<!DOCTYPE html><html><head><meta charset="utf-8"> <meta http-equiv="Content-Script-Type" content="text/javascript"> <title>test</title> </head><body> <form name="form" method="POST" enctype="multipart/form-data"> <label>Text Field 1 <input type="text" name="text_1"></label><br/> <label>Text Field 2 <input type="text" name="text_2"></label><br/> <input type="file" id="file" name="upload"><br/> <input type="submit" name="btn_submit" value="Send"> </form> <pre id="console"></pre> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script><!-- $(function() { $("input[name='btn_submit']").click(function() { var fd = new FormData(document.forms.form); var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : function() { try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { return new ActiveXObject("Microsoft.XMLHTTP"); }} xhr.open("POST", "/doit", true); xhr.onreadystatechange = function(data, status) { if (this.readyState == this.DONE) { $("#console").text(this.responseText); } }; xhr.send(fd); return false; }); }) // --></script> </body></html>''' @bottle.post('/doit') def doit(): bottle.response.set_header('Content-Type', 'text/plain') for key in bottle.request.headers.keys(): yield '{}: {}\n'.format(key, bottle.request.headers[key]) yield '\n' for row in bottle.request.body: yield row yield '=*=*=*=*=*=*=*=*=*=*=\n' for key in sorted(bottle.request.forms.keys()): yield '{}: {}\n'.format(key, bottle.request.forms[key]) for key in bottle.request.files.keys(): yield 'file: {!r}'.format(bottle.request.files[key].filename) if __name__ == '__main__': bottle.debug(True) bottle.run(port=8081, reloader=True) #else: # os.chdir(os.path.dirname(__file__)) # application = bottle.default_app()