在Python和Javascript之间传递变量 [英] Passing variables between Python and Javascript

查看:677
本文介绍了在Python和Javascript之间传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,当更改下拉列表时,您需要编写一些只更改一组复选框的Javascript。

Imagine that you need to write some Javascript that simply changes a set of checkboxes when a drop down list is changed.

取决于列表中选择的项目,一些复选框将被选中/取消选中。

Depending on which item is selected in the list, some of the checkboxes will become checked/unchecked.

在后面,你有Python代码和一些SQLAlchemy。

In the back, you have Python code along with some SQLAlchemy.

Javascript需要像往常一样识别列表中的选定项目,将其发送回Python模块,然后Python模块将使用某些SQLAlchemy中的变量返回需要检查的复选框列表,即用户选择福特',所以复选框'焦点','蒙迪欧','嘉年华'需要检查

The Javascript needs to identify the selected item in the list as usual, send it back to the Python module which will then use the variable in some SQLAlchemy to return a list of checkboxes which need to be checked i.e. "User selected 'Ford', so checkboxes 'Focus', 'Mondeo', 'Fiesta' need to be checked"

我遇到的问题是我似乎无法找到办法从Javascript访问python模块而不将div转换为迷你浏览器页面并将包含变量的url传递给它!

The issue Im having is that I cant seem to find a way to access the python modules from the Javascript without turning a div into a mini browser page and passing a url containing variables into it!

有没有人对如何工作有任何想法?

Does anyone have any ideas on how this should work?

推荐答案

<有趣的是,我有一些带有JavaScript的网页,它与使用SQLAlchemy的Python CGI模块交谈。

Funny, I've got web pages with JavaScript that talk to Python CGI modules that use SQLAlchemy.

我所做的是发送AJAX请求但是在JSON请求中正文而不是XML。 Python CGI模块使用标准 json 将JSON反序列化为字典的模块。

What I do is send AJAX request but with JSON request in the body instead of XML. Python CGI modules use standard json module to deserialize JSON into a dictionary.

JavaScript端看起来像这样:

JavaScript side looks like this:

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传递。

Note, it doesn't use Python cgi module, since the whole request is passed as JSON in the body.

这篇关于在Python和Javascript之间传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆