简体   繁体   English

在 Python 和 Javascript 之间传递变量

[英]Passing variables between Python and Javascript

Imagine that you need to write some Javascript that simply changes a set of checkboxes when a drop down list is changed.想象一下,您需要编写一些 Javascript 来在更改下拉列表时简单地更改一组复选框。

Depending on which item is selected in the list, some of the checkboxes will become checked/unchecked.根据在列表中选择的项目,某些复选框将被选中/取消选中。

In the back, you have Python code along with some SQLAlchemy.在后面,你有 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 ie "User selected 'Ford', so checkboxes 'Focus', 'Mondeo', 'Fiesta' need to be checked" Javascript 需要像往常一样识别列表中的选定项目,将其发送回 Python 模块,然后 Python 模块将使用一些 SQLAlchemy 中的变量返回需要检查的复选框列表,即“用户选择了‘福特’,所以复选框“焦点”、“蒙迪欧”、“嘉年华”需要被选中”

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!我遇到的问题是,我似乎无法找到一种方法来从 Javascript 访问 python 模块,而无需将 div 转换为迷你浏览器页面并将包含变量的 url 传递给它!

Does anyone have any ideas on how this should work?有人对这应该如何工作有任何想法吗?

Funny, I've got web pages with JavaScript that talk to Python CGI modules that use SQLAlchemy.有趣的是,我有一些带有 JavaScript 的网页,这些网页与使用 SQLAlchemy 的 Python CGI 模块对话。

What I do is send AJAX request but with JSON request in the body instead of XML.我所做的是发送 AJAX 请求,但在正文中使用 JSON 请求而不是 XML。 Python CGI modules use standard json module to deserialize JSON into a dictionary. Python CGI 模块使用标准json模块将 JSON 反序列化为字典。

JavaScript side looks like this: 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
});

And Python like this:像这样的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)

Note, it doesn't use Python cgi module, since the whole request is passed as JSON in the body.注意,它不使用 Python cgi 模块,因为整个请求在正文中作为 JSON 传递。

python has a json module, which is a perfect fit for this scenario. python 有一个json模块,非常适合这种情况。

using a good old AJAX, with json as the data format will allow you to exchange data between javascript and your python module.使用良好的旧 AJAX,以 json 作为数据格式将允许您在 javascript 和您的 python 模块之间交换数据。

(unless your python module is running on the client side, but then i don't see how you could execute it from the browser...) (除非您的 python 模块在客户端运行,但是我看不到您如何从浏览器执行它...)

Ajax is a good way to pass variables between python and javascript. Ajax 是在 python 和 javascript 之间传递变量的好方法。 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: (You will need a three functions for this to work) 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)

FYI: "myfunction(a, b, c,)" is a function from another python file, then return the data and passes to self.respond to send back to javascript仅供参考:“myfunction(a, b, c,)”是来自另一个 python 文件的函数,然后返回数据并传递给 self.respond 以发送回 javascript

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

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