在Python和Javascript之间传递变量

15

假设您需要编写一些Javascript代码,当下拉列表更改时,它将简单地更改一组复选框。

根据在列表中选择的项目,一些复选框将变为选中/未选中状态。

在后台,您有带有一些SQLAlchemy的Python代码。

Javascript需要像往常一样识别列表中选择的项,将其发送回Python模块,然后在某些SQLAlchemy中使用该变量返回需要选中的复选框列表,即“用户选择了‘ Ford’,因此需要选中复选框‘ Focus’、‘ Mondeo’、‘ Fiesta’”

我遇到的问题是,我似乎找不到一种方法可以在Javascript中访问Python模块,而不将一个div转换成迷你浏览器页面并将包含变量的URL传递给它!

有人有任何关于如何解决这个问题的想法吗?

3个回答

11
有趣的是,我有一些带有JavaScript的网页,可以与使用SQLAlchemy的Python CGI模块进行通信。
我的做法是发送AJAX请求,但在请求体中使用JSON请求而不是XML。 Python CGI模块使用标准的json 模块将JSON反序列化为字典。
JavaScript端看起来像这样:
function on_request_success(response) {
    console.debug('response', response);
} 

function on_request_error(r, text_status, error_thrown) {
    console.debug('error', text_status + ", " + error_thrown + ":\n" + r.responseText);
}

var request = { ... };
jQuery.ajax({
    url: 'http://host/whatever.cgi',
    type: 'POST',
    cache: false,
    data: JSON.stringify(request),
    contentType: 'application/json',
    processData: false,
    success: on_request_success,
    error: on_request_error
});

而 Python 喜欢这样:

request = json.load(sys.stdin)
response = handle_request(request)
print("Content-Type: application/json", end="\n\n")
json.dump(response, sys.stdout, indent=2)

请注意,它不使用Python cgi模块,因为整个请求作为JSON在正文中传递。


6

Python有一个json模块,非常适合这种情况。

使用良好的老式AJAX,以json作为数据格式,将允许您在JavaScript和Python模块之间交换数据。

(除非您的Python模块正在客户端运行,但是我不知道您如何从浏览器执行它...)


0

Ajax是在Python和JavaScript之间传递变量的好方法。 JavaScript:

 param = {a:'hello', b: 'world', c: '!'}
   

        $.ajax({
            type: "post",
            url: "scpi.py",
            cache: false,
            async: 'asynchronous',
            dataType: 'html',
            data: param,
            success: function(data) {
                console.log(data)
               
            },
            error: function(request, status, error){
                console.log("Error: " + error)
            }
        })

Server.py: (为了使其工作,您需要三个函数)

    def do_POST(self):
    if "scpi.py" in self.path:
        form = cgi.FieldStorage(
            fp=self.rfile,
            headers=self.headers,
            environ={'REQUEST_METHOD': 'POST'}
        )
        a = form['a'].value
        b = form['b'].value
        c = form['c'].value

        content = myfunction(a, b, c)
        self.respond(content)      

def handle_http(self, data):
    self.send_response(200)
    self.send_header('Content-type', 'application/json')
    self.end_headers()
    print(data)
    return bytes(str(data), 'UTF-8')
    
def respond(self, data):
    response = self.handle_http(data)
    print(data)

提示: "myfunction(a, b, c,)" 是另一个Python文件中的函数,然后返回数据并传递给self.respond以发送回JavaScript


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接