在 python 中检索 XMLHttpRequest 参数

发布于 2024-07-12 08:39:29 字数 425 浏览 3 评论 0原文

客户端代码通过 ajax 请求向 python cgi 脚本提交对象(在 POST 请求正文中)或查询字符串(如果使用 GET 方法)。 请注意,对象/查询字符串参数不是来自

<form> or <isindex>.

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

非常感谢

编辑:
@codeape:谢谢,但这不是只适用于提交的表单吗? 就我而言,没有提交任何表单,只是一个异步请求。
使用您的脚本,如果没有提交表单,则 len(f.keys()) 返回 0! 我也许可以将请求重新编写为表单提交,但是有更好的方法吗?

Client-side code submits an object (in the POST request body) or query string (if using GET method) via ajax request to a python cgi script. Please note that the object/query string parameters are not coming from a

<form> or <isindex>.

How can I retrieve these parameters from within the server-side python script using standard library modules (e.g., cgi)?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不必在意 2024-07-19 08:39:30

@codeape@bruno desthuilliers

事实上,cgi.FieldStorage() 检索参数。 我之前得到的输出显然是由于我在请求正文中将参数作为字符串(JSON.stringify() 对象)传递的,而不是作为键值对传递的。
谢谢

@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

梦罢 2024-07-19 08:39:29

您使用 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))

You use the cgi.FieldStorage class. Example CGI script:

#! /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))
初与友歌 2024-07-19 08:39:29

codeape已经对此做出了回答。 仅作为记录,请理解 HTTP 请求的发出方式是完全正交的 - 服务器收到的是 HTTP 请求,就这样。

codeape already answered on this. Just for the record, please understand that how the HTTP request is emitted is totally orthogonal - what the server get is an HTTP request, period.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文