5

重複の可能性:
JSON を Python CGI にポストする

Apache2 がインストールされ、Python が動作しています。

私は問題を抱えています。2ページあります。

1 つは Python ページで、もう 1 つは JQuery を使用した Html ページで、Src を Google jquery リンクに貼り付けることができませんでした。

誰かが私のajax投稿を正しく機能させる方法を教えてください。

    $(function()
    {
        alert('Im going to start processing');

        $.ajax({
            url: "saveList.py",
            type: "post",
            data: {'param':{"hello":"world"}},
            dataType: "application/json",
            success : function(response)
            {
                alert(response);
            }
        });
    });

そしてPythonコード

import sys
import json

def index(req):
    result = {'success':'true','message':'The Command Completed Successfully'};

    data = sys.stdin.read();

    myjson = json.loads(data);

    return str(myjson);
4

1 に答える 1

19

以下は、html ファイルの例とそれに付随する python CGI スクリプトです。

このhtmlを使用:

<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">

        <title>test</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script>

            $(function()
            {
                $('#clickme').click(function(){
                    alert('Im going to start processing');

                    $.ajax({
                        url: "/scripts/ajaxpost.py",
                        type: "post",
                        datatype:"json",
                        data: {'key':'value','key2':'value2'},
                        success: function(response){
                            alert(response.message);
                            alert(response.keys);
                        }
                    });
                });
            });

        </script>
    </head>
    <body>
        <button id="clickme"> click me </button>
    </body>

</html>

そしてこのスクリプト:

#!/usr/bin/env python

import sys
import json
import cgi

fs = cgi.FieldStorage()

sys.stdout.write("Content-Type: application/json")

sys.stdout.write("\n")
sys.stdout.write("\n")


result = {}
result['success'] = True
result['message'] = "The command Completed Successfully"
result['keys'] = ",".join(fs.keys())

d = {}
for k in fs.keys():
    d[k] = fs.getvalue(k)

result['data'] = d

sys.stdout.write(json.dumps(result,indent=1))
sys.stdout.write("\n")

sys.stdout.close()

ボタンをクリックすると、cgi スクリプトが次のように返されることがわかります。

{
 "keys": "key2,key", 
 "message": "The command Completed Successfully", 
 "data": {
  "key2": "value2", 
  "key": "value"
 }, 
 "success": true
}
于 2012-05-23T17:18:42.537 に答える