简体   繁体   English

如何从javascript运行python函数?

[英]How to run python function from javascript?

I have a problem in calling my python function from my javascript file.我在从我的 javascript 文件调用我的 python 函数时遇到问题。

I'm using a simple server with python3 -m http.server , so no actual backend..my javascripts are in the front end.我正在使用带有python3 -m http.server的简单服务器,所以没有实际的后端..我的 javascripts 在前端。

I have a python file called write.py it has a function that I want to execute from my javascript file我有一个名为write.py的 python 文件,它有一个我想从我的 javascript 文件中执行的函数

write.py file:写.py文件:

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)我尝试过的 javascript 部分:(但没有用)

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

xmlDoc is a string that has an xml document. xmlDoc是一个包含 xml 文档的字符串。

name is a variable that has the name of the file for the python function. name是一个变量,它具有 python 函数的文件名。

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?所以我的问题是,从我的 js 文件中调用write.py或者如果这种方法错误如何调用它,我缺少什么?

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.您正在使用 http.server 将文件夹的内容作为文件提供,而不是执行它们,因此在最好的情况下,http.server 将响应write.py文件的内容,而不是执行它。

You need to create a webserver that has a endpoint where the code of write.py is integrated.您需要创建一个具有集成 write.py 代码的端点的网络服务器。

You can't send a POST http request to run a python script.您不能发送 POST http 请求来运行 python 脚本。

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.您需要在服务器上运行 python 脚本,该脚本能够进行安静的 API 调用,以运行脚本并返回一个值。

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.例如,您可以运行一个接收 POST 路由的小 Flask 应用程序,该应用程序运行一个脚本并将脚本的值返回给访问 POST 路由的客户端。

Python is running on the server side ... JavaScript is running on the client side. Python 在服务器端运行…… JavaScript 在客户端运行。

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.因此,JavaScript 要求运行 Python 例程的唯一方法是通过您必须构建的异步 AJAX 请求。

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

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