将值从 html 传递到 python

Pass value from html to python

我正在使用 Xamp。 我有一个表格。

<form action=/cgi-bin/run.py>    
<input type="text" name="ins" id="ins">
<input type="submit" id="sub" value="submit">   
</form>
#Tag to display output from form input
</div>
<div class="output" name="output" id="output">
</div>

点击提交按钮。文本输入是我的 py 脚本的输入。 并且输出显示在浏览器中的一个 div 标记中。

将 python 脚本的输出显示回浏览器。我用JS.

 $(sub).click(function(){ 
$.ajax({
                type:'GET',
                url:'/cgi-bin/t1.py', 
                cache:false,                
                dataType: 'html',                                        
                success:function (z) {
                     $('#output').html(z);
                }                
        });

    });

我的python脚本:

#!"C:\Programs\Python\Python36-32\python.exe"
import cgi, cgitb
print("Content-Type: text/html \n\n")
form = cgi.FieldStorage()

count1=form.getvalue('ins')
print(count1)

如果我给表格 action=/cgi-bin/run.py 我的 js 不会在单击按钮时执行。 如果 js 不执行,那么我的输出将不会重定向到同一页面。 它将在单独的页面中显示 python 脚本的输出。 有解决此问题的方法吗?

单击按钮我需要 运行 py 脚本(接受 html 的输入)并在 div 标签中显示输出。

尝试回答,尽管我仍然不能 100% 确定您的意思。尝试将您的 Javascript 更改为:

$(sub).click(function(ev){
    ev.preventDefault(); // Stop the form from redirecting the page.
    $.ajax({
            type:'GET',
            url:'/cgi-bin/t1.py', // Or /cgi-bin/run.py. I'm not sure where your python script is.
            cache:false,
            dataType: 'html',
            data: $('form').serialize(), // Send the form data in the request.
            success:function (z) {
                 $('#output').html(z);
            }
    });

});