11
13

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 3 years have passed since last update.

python + ajaxのPOST通信

Last updated at Posted at 2018-12-18

python + ajaxのPOST通信のサンプルコードです。
jQuery使ってます。

###クライアント側

sample.js

let samplePost = function(){

    //レスポンス
    var response = {};

    //リクエスト
    let request = {para_1 : 12,
                   para_2 : "aaaa",
                   para_3 : encodeURI("日本語送信")};

    //ajax
    $.ajax({
      type        : "POST",
      url         : url,
      data        : JSON.stringify(request),  //object -> json
      async       : false,                    //true:非同期(デフォルト), false:同期
      dataType    : "json",
      success     : function(data) {
        //data = JSON.parse(data);  //error
        response = data;
      },
      error       : function(XMLHttpRequest, textStatus, errorThrown) {
        console.log("リクエスト時になんらかのエラーが発生しました\n" + url + "\n" + textStatus +":\n" + errorThrown);
      }
    });

    //表示
    console.log(response);
}

###サーバ側

sample.py
#!/usr/bin/python
# -*- coding: utf-8 -*-


#######################################################
#
#  import
#
#######################################################

import cgitb
import cgi
import os
import json
import sys
import io
import urllib.parse  #url encode/decode


#######################################################
#
#  main
#
#######################################################
def main():

    #文字化け対策
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

    #エラーの内容をブラウザに送信
    cgitb.enable()

    #値取得
    data   = sys.stdin.read()
    params = json.loads(data)

    #
    para_1 = params["para_1"]
    para_2 = params["para_2"]
    para_3 = params["para_3"]  #url encoded

    #url decode
    para_3 = urllib.parse.unquote(para_3)


    #######################################################
    #
    #  処理
    #
    #######################################################

    #処理

    #レスポンス
    response = {"res" : "aaaa"}


    #######################################################
    #
    #  response
    #
    #######################################################

    #print("Content-type: application/json")  #error
    print('Content-type: text/html\nAccess-Control-Allow-Origin: *\n')
    print("\n\n")
    print(json.JSONEncoder().encode(response))
    print('\n')


################################################
#
#  main実行
#
################################################
if __name__ == '__main__':
    main()

追記

python cgiでInternal Server Error(500)が出た時の対処法
https://qiita.com/qiiChan/items/f599fbf2289801348965

11
13
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
11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?