我在树莓派中运行python脚本和apache网络服务器。我想使用JavaScript从网页更改python脚本中变量的值。有可能吗?
答案 0 :(得分:0)
我们可以使用套接字。为了方便使用套接字,我们可以使用socket.io
Start.html
<!doctype html>
<html>
<head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
</head>
<body>
<h1>Socket.IO GPIO control</h1>
<button id="btnGpio">Change GPIO</button>
<script>
var socket = io.connect('http://localhost:5000');
var index = 0;
socket.on('connect', function () {
console.log('connected')
document.getElementById('btnGpio').addEventListener('click', () => {
index = index + 1;
console.log('index', index)
socket.emit('change_gpio', { status: (index % 2 == 0) })
})
});
</script>
</body>
</html>
socket_server.py
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
@app.route("/")
def home():
return render_template("Start.html")
socketio = SocketIO(app)
pin = True
@socketio.on('change_gpio')
def handle_my_custom_event(json):
pin = json['status']
print('pin = ' , pin)
@socketio.on('connect', namespace='/')
def test_connect():
print('Connected')
if __name__ == '__main__':
socketio.run(app)
使用pip安装库
pip install flask
pip install flask-socketio