English 中文(简体)
在Python中检索XMLHttpRequest参数
原标题:
  • 时间:2009-01-15 07:38:42
  •  标签:

客户端代码通过ajax请求将对象(在POST请求主体中)或查询字符串(如果使用GET方法)提交给Python cgi脚本。请注意,对象/查询字符串参数不是来自于一个。

<form> or <isindex>.

我如何使用标准库模块(例如,cgi)从服务器端Python脚本中检索这些参数?

Thanks very much

EDIT:
@codeape: Thanks, but wouldn t that work only for submitted forms? In my case, no form is being submitted, just an asynchronous request.
Using your script, len(f.keys()) returns 0 if no form is submitted! I can probably recast the request as a form submission, but is there a better way?

问题回答

您可以使用cgi.FieldStorage类。示例CGI脚本:

#! /usr/bin/python

import cgi
from os import environ
import cgitb
cgitb.enable()

print "Content-type: text/plain"
print
print "REQUEST_METHOD:", environ["REQUEST_METHOD"]
print "Values:"
f = cgi.FieldStorage()
for k in f.keys():
    print "%s: %s" % (k, f.getfirst(k))

codeape已经回答了这个问题。仅供记录,要理解的是,HTTP请求的发出方式是完全正交的 - 服务器接收到的是HTTP请求,没有其他。

@codeape , @bruno desthuilliers:

Indeed, cgi.FieldStorage() retrieves the parameters. The output I was getting earlier was apparently due to my passing the parameters as a string (JSON.stringify() object) in the body of the request -- rather than as key-value pairs.
Thanks





相关问题
热门标签