简体   繁体   中英

How to run python function from javascript?

I have a problem in calling my python function from my javascript file.

I'm using a simple server with python3 -m http.server , so no actual backend..my javascripts are in the front end.

I have a python file called write.py it has a function that I want to execute from my javascript file

write.py file:

def save_vit(text,name):
    f = open(name + ".xml", "w+")
    f.write(text)
    f.close()

the javascript part that i have tried:(but didn't work)

$.ajax({
        type: "POST",
        url: "write.py",
        data: { text: xmlDoc,name: name}});

xmlDoc is a string that has an xml document.

name is a variable that has the name of the file for the python function.

So my question is, what am I missing to call write.py from my js file or how to call it if this approach is wrong?

You are using http.server to serve the content of a folder, as files, not to execute them, so in the best case scenario, http.server will respond with the content of the write.py file instead of executing it.

You need to create a webserver that has a endpoint where the code of write.py is integrated.

You can't send a POST http request to run a python script.

You need to have the python script running on a server, that is able to take restful API calls, to run the script and return a value.

For example, you can run a small flask app that takes in your POST route, which runs a script and returns the value of the script back to the client that accessed the POST route.

Python is running on the server side ... JavaScript is running on the client side.

So, the only way for JavaScript to ask for a Python routine to be run is through an asynchronous AJAX request which you will have to build.

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