开发者

Passing variables between Python and Javascript

开发者 https://www.devze.com 2023-04-11 17:44 出处:网络
Imagine that you need to write some Javascript that simply changes a set of checkboxes when a drop down list is changed.

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.

In the back, you have Python code along with some 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"

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?


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

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 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
});

And Python like this:

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 has a json module, which is a perfect fit for this scenario.

using a good old AJAX, with json as the data format will allow you to exchange data between javascript and your python module.

(unless your python module is running on the client side, but then i don't see how you could execute it from the browser...)


Ajax is a good way to pass variables between python and 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)

    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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号