简体   繁体   中英

Is there any alternative to implement javascript`s onClick() function in pure python?

In short: I'm looking is to get the img src value onClick() & pass that selected image to a python function to work with PIL

say, var i = getElementById("image-id").src pass this to python def whatever(): img = src var from js fun

Is it possible? I know this can be done >>>

def post(self):
    val = self.request.get("name_of_the_txt_field_to_get")
    self.request.write("val") 

but I want the variable to a be an image SRC with a onClick(); button function, and I want to pass this SRC value to the python function as a variable.

I'm aware that js is client side & python is server side, So I'm looking to pass the value to another URL say from http://localserver to http://localserver/image

I've been finding a solution to it & I did came across some options: https://github.com/atsepkov/RapydScript (but it's a python to javascript compiler & I'll need to compile it)

another one is the good old http://code.google.com/p/pyv8/ but I can't figure it out &

this one seems to be pretty interesting PICO & I think would get the job done, however I can't figure it on how do I run it on GAE

workspace: GAE for python with Jinja2 Template.

You could use jQuery to do an AJAX POST to http://localserver/image :

$(document).ready(function() {
    $("img").click(function() {
        var request = $.ajax({
            url: "/image",
            type: "POST",
            data: {imageSrc : $(this).attr("src")}
        });

        request.done(function(msg) {
            alert("Request succeeded: " + msg );
        });

        request.fail(function(jqXHR, textStatus) {
            alert( "Request failed: " + textStatus );
        });
    });
});

See also: Ajax tutorial for post and get

I'm assuming you're asking about Javascript because you're running something in a web browser. And when you run something in a browser, I assume you want things to run in any browser.

In which case, the answer is no, there isn't.

Browsers can execute Javascript. They don't execute python. So you will need to execute Javascript in the browser, make some sort of HTTP request to your server, and process the request in python. There's libraries like pico that generate wrappers so you have to write less code, but it does the same thing in the background.

You could write some sort of plugin for browsers that can execute python. It's been done: https://wiki.python.org/moin/WebBrowserProgramming

But you'll be limited to a subset of browsers who have the appropriate plugin installed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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