LoginSignup
1
2

More than 1 year has passed since last update.

CGIを用いたJavaScript-Pythonのajax通信

Posted at

はじめに

HTMLのbuttonをクリックすると、JavaScriptがPythonにデータを受け渡し、Pythonが受け取ったデータを加工してJavascriptに返すプログラムを書いてみる。

ディレクトリ構成

.
├ cgi-bin/
    └ sample.py
├ index.html
├ style.css
└ index.js

cgi-binフォルダはホームディレクトリ直下に置く必要があるみたい。

HTMLの記述

index.html
<!DOCTYPE html>
    <html lang="ja">
        <head>
            <meta charset="UTF-8">
            <title>タイトル</title>
            <meata name="viewport" content="width=device-width,initial-scale=1"></meata>
            <link rel="stylesheet" href="style.css"> 
        </head>
        <body>
            <button type="button" name="テスト" value="test">テスト</button>
            <script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
            <script src="index.js"></script>
        </body>
    </html>

今回はajaxをjQueryで記述するので、index.jsを読み込む前にjQueryのCDNを読み込む。

公式URL→https://releases.jquery.com/
*「uncompressed」は何かエラーが起きたときに要因が分かる。

JavaScript(jQuery)の記述

buttonをクリックするとajaxで"{set:"test"}"というjsonデータをpythonに送るプログラムをjQueryで記述。

pythonから返されたデータはコンソールに表示。
エラーの際はコンソールに"failed"と表示。

index.py
$(function(){
    $("button").click(function(){
        $.ajax({
            url:'./cgi-bin/sample.py',
            type:'POST',
            data:{sent:"test"}
        })
        .done(function(data){
            console.log(data);
        })
        .fail(function(){
        console.log("failed");
        });
    });
});

Pythonの記述

sample.py
#!/〇〇/python3
# -*- coding: utf-8 -*-

import cgi
import cgitb
import json

cgitb.enable()
form=cgi.FieldStorage()
data=form.getvalue("sent")
receive=data+"OK"
print("Content-type: text/html\n")
print(receive)

1行目のシバンはプログラムをどうやって実行するかを示す。
シバンはbashから調べられる。

$ which python3

cgitb モジュールの enable() は、CGIスクリプトの実行時に発生したエラーの内容をブラウザに送信してくれる。

cgiモジュールのFieldStorage()は、フォームの内容を受け取るときに使える。
getvalue()で指定したkeyのjsonデータを受け取る。

実行

1.cgi-binと実行ファイルに実行権限を与える。

$ chmod -R +x cgi-bin

chmodは「ファイル」「ディレクトリ」のアクセス権を変更するためのコマンド。

2.pythonのローカルサーバを立ち上げる

$ python -m http.server --cgi

下記のように表示されたら、サーバの立ち上げ成功。
今回はポート番号は指定していないので、表示された8000がポート番号になる。

実行結果
$ python -m http.server --cgi
Serving HTTP on :: port 8000 (http://[::]:8000/)

3.ブラウザで実行できるか確認

今回はGooglechromeを使用した。

index.htmlを表示するURL→http://localhost:8000/

ポート番号が異なる場合は8000のところを指定されたポート番号に変更して検索するとindex.htmlが表示される。

chromeのデバロッパーツールでコンソールを確認できる。
デバロッパーツールはwindowsの場合、Shift+Ctrl+Iで見ることができる。

参考資料

神田幸恵『jQuery標準デザイン講座』,翔泳社,2015.

まとめ

HTMLのbuttonをクリックすると、JavaScriptがPythonにデータを受け渡し、Pythonが受け取ったデータを加工してJavascriptに返すプログラムを作成した。

実行するには、
1.cgi-binフォルダに実行権限を付与
2.ローカルサーバの立ち上げ
3.ブラウザで実行結果を確認

1
2
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
2