简体   繁体   English

通过JQuery AJAX调用使用Python CGI FieldStorage访问字段

[英]Accessing fields with Python CGI FieldStorage from a JQuery AJAX call

I have written some JQuery that makes an ajax call to a Python script. 我写了一些JQuery,可以对Python脚本进行ajax调用。 I've been successful in passing strings back and forth between them, but I'm getting weird behaviour from the CGI FieldStorage object that I'm using to get the input in the Python script. 我已经成功地在字符串之间来回传递了字符串,但是我从CGI FieldStorage对象中获得了奇怪的行为,该对象用于获取Python脚本中的输入。 I've also managed to send a simple object with key/value pairs, like this: 我还设法发送了一个具有键/值对的简单对象,如下所示:

deptObj = { one : '1', two : '2'};

$.ajax({
    data: deptObj,
    url: "simple.py",
    success: function(result) { console.log("Success!"); console.log(result); },
    error: function(request, error) { console.log("Error"); console.log(request); }
});

Here is my python script, simple.py: 这是我的python脚本simple.py:

#!/usr/bin/env python
import json
import cgi
import cgitb

print "Content-type: application/json\n\n" 
cgitb.enable() # display error messages in web browser

fs = cgi.FieldStorage()

print json.dumps(fs.keys())

When I run the javascript, it correctly prints out the keys in my object, ie ["two", "one"] (I'm not sure why they're reversed). 当我运行JavaScript时,它会正确打印出对象中的键,即["two", "one"] (我不确定为什么它们会被反向)。 I can also get the corresponding values by replacing the last line of simple.py with something like print json.dumps(fs["one"].value) . 我还可以通过将simple.py的最后一行替换为print json.dumps(fs["one"].value)来获取相应的值。

However, when I try to make a multi-level object (an object within an object), I get weird behaviour. 但是,当我尝试制作一个多级对象(一个对象中的一个对象)时,我会感到奇怪。 For example, I kept the deptObj that I had already created, then passed in data: { departments: deptObj} to the ajax call. 例如,我保留了已经创建的deptObj,然后将data: { departments: deptObj}传递给ajax调用。 Then, when I tell simple.py to print out the keys, the result is ["departments[two]", "departments[one]"] instead of what I would expect, ["departments"] . 然后,当我告诉simple.py打印出键时,结果是["departments[two]", "departments[one]"]而不是我期望的["departments"] Then, since "departments" is apparently not a key, I get a KeyError when I try print json.dumps(fs["departments"].value) , while print json.dumps(fs["departments[one]"].value) gives me a result of 1. 然后,由于“部门”显然不是键,因此当我尝试print json.dumps(fs["departments"].value) ,却出现了print json.dumps(fs["departments[one]"].value) ,而同时print json.dumps(fs["departments[one]"].value)给我的结果是1。

According to the documentation for FieldStorage , "the fields, accessed through form[key], are themselves instances of FieldStorage", so I thought that my FieldStorage object would have a "departments" key whose value is another FieldStorage object containing the keys "one" and "two". 根据FieldStorage文档 ,“通过form [key]访问的字段本身就是FieldStorage的实例”,因此我认为FieldStorage对象将具有一个“部门”键,其值是另一个包含键“ one”的FieldStorage对象。 ”和“两个”。 However, this doesn't seem to be true. 但是,这似乎并不正确。 How do I form a multi-level Javascript object and access it in my python script using FieldStorage? 如何形成一个多级Javascript对象并使用FieldStorage在我的python脚本中访问它?

This is just jQuery being silly. 这只是jQuery是愚蠢的。 You should set traditional: true in your $.ajax call. 您应该在$.ajax调用中将traditional: true设置为traditional: true

This will not strictly answer your question but I hope it answers the goal rather than the specifics of what you asked. 这不会严格回答您的问题,但我希望它能回答目标而不是您提出的具体问题。 I'm sorry if it's not what you wanted. 抱歉,这不是您想要的。

jQuery passing the Ajax request whose content type is (by default) application/x-www-form-urlencoded; charset=UTF-8 jQuery传递Ajax请求,其内容类型(默认情况下)为application/x-www-form-urlencoded; charset=UTF-8 application/x-www-form-urlencoded; charset=UTF-8 (taken from the jQuery (v1.0 and later) documentation ). application/x-www-form-urlencoded; charset=UTF-8 (摘自jQuery(v1.0及更高版本)文档 )。

There are a few ways to get the JSON into your python script from the JavaScript. 有几种方法可以从JavaScript将JSON导入python脚本。 The first is to explicitly make a form field and pass in the 'stringified' JSON structure which you can then parse at the other end. 首先是显式地创建一个表单字段,并传入“字符串化” JSON结构,然后可以在另一端进行解析。 Another is to try and reverse engineer how jQuery is encoding the JSON string and pick apart the encoded fields into a JSON string (which sounds painful). 另一个方法是尝试反向工程化jQuery如何编码JSON字符串,然后将编码后的字段分离成JSON字符串(听起来很痛苦)。

There is (in my opinion) a better way, which passes the content type as JSON straight away by specifying the content type to be JSON in the Ajax query. (在我看来)有一种更好的方法,可以通过在Ajax查询中将内容类型指定为JSON来立即将内容类型作为JSON传递。 For example, changing your jQuery Ajax call to: 例如,将您的jQuery Ajax调用更改为:

deptObj = { one : '1', two : '2'};

$.ajax({
    data: deptObj,
    type: "POST",
    url: "simple.py",
    dataType : "json",
    success: function(result) { console.log("Success!"); console.log(result); },
    error: function(request, error) { console.log("Error"); console.log(request); }
});

(that is, adding the type to 'POST' and adding the dataType to 'json' ). (即,将type添加到'POST'并将dataType添加到'json' )。 And the corresponding Python code: 以及相应的Python代码:

#!/usr/bin/env python
import json
import sys
import cgi
import cgitb
cgitb.enable() # display error messages in web browser

print "Content-type: application/json\n\n" 
print json.dumps( json.load( sys.stdin ) )

yields what I believe to be your desired result. 产生了我认为是您想要的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM