在html文件中调用python函数

has*_*anm 12 html python

有没有办法在html页面中单击某个链接时调用python函数?

谢谢

Ble*_*der 21

您需要使用Web框架将请求路由到Python,因为您不能仅使用HTML.Flask是一个简单的框架:

server.py:

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
  return render_template('template.html')

@app.route('/my-link/')
def my_link():
  print 'I got clicked!'

  return 'Click.'

if __name__ == '__main__':
  app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)

templates/template.html:

<!doctype html>

<title>Test</title> 
<meta charset=utf-8> 

<a href="/my-link/">Click me</a>
Run Code Online (Sandbox Code Playgroud)

运行它,python server.py然后导航到http:// localhost:5000 /.开发服务器不安全,因此要部署应用程序,请查看http://flask.pocoo.org/docs/0.10/quickstart/#deploying-to-a-web-server

  • @PraveshJain:哦,对不起,如果我不清楚的话.你需要把`template.html`放到`templates`文件夹中. (2认同)

Mic*_*yan 6

是的,但不是直接的; 您可以设置onclick处理程序以调用将构造XMLHttpRequest对象并将请求发送到服务器上的页面的JavaScript函数.反过来,您的服务器上的那个页面可以使用Python实现并执行它需要做的任何事情.