Javascript 如何使用ajax将字符串传递给python程序,并将字符串发送回

Javascript 如何使用ajax将字符串传递给python程序,并将字符串发送回,javascript,python,ajax,Javascript,Python,Ajax,我有一个ajax请求,使用json向python程序发送一个对象: $.ajax({ url: "http://localhost/cgi-bin/python.cgi", type: "POST", data: JSON.stringify(myobject), dataType: "text", success: function(response){ console.log("it's

我有一个ajax请求,使用json向python程序发送一个对象:

$.ajax({
        url: "http://localhost/cgi-bin/python.cgi",
        type: "POST",
        data: JSON.stringify(myobject),
        dataType: "text",
        success: function(response){
            console.log("it's alive");
            console.log(response)
        },
        error: function(){
            alert('request failed');
        }
})
python.cgi看起来像

import cgitb
cgitb.enable()
import sys, json

input =sys.stdin

output = json.loads(input)

json.dumps(output, sys.stdout)
这个密码给了我

TypeError:json对象必须是“str”而不是“TextIOWrapper”

我不明白为什么会发生这种情况,因为我将数据作为字符串传递

感谢您的帮助。

如中所述,您可能应该使用FieldStorage类,而不是直接从标准输入读取:

import cgi

print "Content-Type: application/json"
print

form = cgi.FieldStorage()

表单中
您就可以访问所需的数据

如果您尝试
json.load
(而不是
json.load
)该怎么办。前者对类似文件的对象进行操作,后者对字符串进行操作。这样做会产生500个内部服务器错误。此外,我假设您切换到了
json.dump
,而不是
json.dumps
?我没有-愚蠢的我-但它给了我相同的结果stdin是类似文件的对象,请尝试
sys.stdin.read()
。应该是
内容类型吗?看起来OP试图返回一个json响应,所以我不确定您的内容类型是否正确:-)