简体   繁体   English

如何调用将 javascript 值作为参数传递给 python function

[英]How to call pass javascript value as parameter to python function

I have a HTML input and onClick with a button, I get the value of text input and store in a varibale in Javascipt.我有一个 HTML 输入和一个带有按钮的 onClick,我得到文本输入的值并存储在 Javascipt 的变量中。 Now how can I use this varibale as a paramter to a python function?现在我如何使用这个变量作为 python function 的参数?

In JavaScript I have:在 JavaScript 我有:

var text = document.getElementById("text").value;

and in Python I have:在 Python 中我有:

someFunction(text):
   print(text) # text is what I want to be passed from javascript

I am using pyscript to run my python codes我正在使用 pyscript 运行我的 python 代码

You can submit the form to send values to a Python file or use API's with Ajax this article about difference between server-side and client-side .您可以提交表单以将值发送到 Python 文件或将APIAjax这篇关于服务器端和客户端之间的区别的文章一起使用。

And in regard to @JohnHanley comment you can use py-script to do that, take a look here关于@JohnHanley 的评论,您可以使用py-script来做到这一点,请看这里

 <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> <script defer src="https://pyscript.net/latest/pyscript.js"></script> <script> name = "Guido" //A JS variable // Define a JS Function function addTwoNumbers(x, y){ return x + y; } </script> <py-script> # Import and use JS function and variable into Python from js import name, addTwoNumbers print(f"Hello {name}") print("Adding 1 and 2 in Javascript: " + str(addTwoNumbers(1, 2))) </py-script>

You can do a GET or a POST from your page to the python script.您可以从您的页面执行 GET 或 POST 到 python 脚本。 AJAX makes this quite easy for you - there is an existing answer to a similar question here on stack, have a look at: AJAX 让这对你来说很容易 - 堆栈上有一个类似问题的现有答案,看看:

Passing Javascript variable to Python 将 Javascript 变量传递给 Python

You might find it easier to parcel up the variable in a little json, which makes the GET/POST nice and simple, then import json in your python code and modify the function accordingly.您可能会发现将变量打包到一个小的 json 中会更容易,这使得 GET/POST 变得既好又简单,然后在您的 python 代码中import json并相应地修改 function。

Also probably need to define an endpoint so the server knows to execute the python script还可能需要定义一个端点,以便服务器知道执行 python 脚本

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

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