【问题标题】:python cgi script prints object as a string when raw string is sent using javascriptpython cgi脚本在使用javascript发送原始字符串时将对象打印为字符串
【发布时间】:2015-11-27 11:53:54
【问题描述】:

我正在使用 javascript 将数据{"hello":"world"}; 发送到 python cgi 脚本,如下所示(此脚本有效)

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<head>I am a header</head>
<body>
<script type="text/javascript">
var httprequest=new XMLHttpRequest();
httprequest.open("POST","hello.cgi");
var content={"hello":"world"};
httprequest.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
httprequest.send(JSON.stringify(content));
httprequest.onload=function(){
if(httprequest.status==200){
alert("");
document.write(httprequest.responseText)};
}//end of onload
</script>
</body>
<script>
</script>
</html>
</doctype>

这是我的 python cgi 脚本

#!/usr/bin/python
try:
    import sys,os
    import cgi
    sys.stderr=sys.stdout
    import traceback
    print("Content-type: text/html\n\n")
    print "<h1>YES</h1>"
    formData = cgi.FieldStorage()
    print((formData))
except Exception as e:
    #print(e.message)
    print(traceback.print_exc())

此 cgi 脚本将 javascript 对象转换为字符串,擦除 html 文档中的所有内容并将以下内容写入浏览器

  YES
FieldStorage(None, None, '{"hello":"world"}') 

问题 1

我确实希望此 cgi 脚本将 '{"hello":"world"}' 写为字段存储中的 字符串 我希望它将字符串写为字典 {"hello":"world"} /object

或者在 javascript 中是否有一种方法可以将 javascript 字符串编码为 GET 或 post 格式并将输出发送,就好像它正在将带有数据的 html &lt;form&gt; 提交到 python cgi 脚本一样?这会解决这个问题吗?

【问题讨论】:

    标签: javascript python xmlhttprequest


    【解决方案1】:

    看来 cgi.fieldstorage 主要用于从 HTML 表单标签接收数据。因此它不是 json 字符串的正确工具

    这是我在深夜精神崩溃后解决此问题的方法。我在 python 中使用 json 模块

    #!/usr/bin/python
    try:
        import sys,os,json
        import cgi
        sys.stderr=sys.stdout
        import traceback
        print("Content-type: text/html\n\n")
        print "<h1>YES</h1>"
        data=json.load(sys.stdin) #convert json string to python object (answer)
        print "<script>var t="+str(json.dumps(data))+"</script>" # I can also take the string and put it in a html script
        #print((formData))
    except Exception as e:
        print(e.message)
        print(traceback.print_exc())
    

    之后我尝试在浏览器中调用我的 javascript 对象 t 并且它按预期工作..真是一种解脱...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 2020-07-12
      • 2017-02-14
      • 2016-12-29
      • 2011-07-14
      相关资源
      最近更新 更多