【问题标题】:AJAX Posting to Python cgi [duplicate]AJAX 发布到 Python cgi [重复]
【发布时间】:2026-01-28 09:40:01
【问题描述】:

可能重复:
Post JSON to Python CGI

我已经安装了 Apache2 并且 Python 工作正常。

我有一个问题。我有两页。

一个是 Python 页面,另一个是带有 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);

【问题讨论】:

  • 请不要打开您的问题的多个副本。

标签: jquery python html ajax


【解决方案1】:

这是一个示例 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
}

【讨论】:

  • 我得到 undefined 而不是它应该返回的内容
  • 无论我在 localhost 或 Google Cloud 上运行它,我都会得到“不受支持的方法(“post”)”。
  • 使用这个例子 fs = cgi.FieldStorage() 也没有给我任何由 Ajax 'data' 参数发送的键/值对。我使用了 fs = sys.stdin.read() 而不是 cgi.FieldStorage(),它给出了一个格式字符串:key=value&key2=value2。从这里你可以使用 d = dict(item.split("=") for item in fs.split("&")) 创建一个 python 字典另外,使用 print() 比 sys.stdout.write() 更好,因为print() 自己添加一个换行符。它还会自动将参数转换为字符串。因此,对于上面 python 脚本中的最后三行,您可以使用: print(json.dumps(result,indent=1))
最近更新 更多