나는 새로운 python 및 Flask. 나는 플라스크 웹 앱 단추입니다. 때 나는 버튼을 클릭하고 싶은 실행이 없는 방법을 자바 스크립트 방법입니다. 이렇게 하려면 어떻게 해야 합니까?
본 예제는 파이썬치로 리디렉션하는 새로운 페이지 양식을 사용하여 이 같은 태그
<form action="/newPage" method="post">
하지만 나는't 고 싶은 날로 새로운 페이지입니다. 나는 그냥 그것을 실행하는 파이썬은 방법입니다. 내가 이를 위한 라즈베리 파이 로봇이 차. 누를 때 나는 앞으로 단추,나는 그것을 실행하는 방법을 바퀴 돌니다.
버튼을 HTML 코드(index.html)
<button name="forwardBtn" onclick="move_forward()">Forward</button>
단 app.py 코드 move_forward()method 여기에 있는
#### App.py code
from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html');
def move_forward():
#Moving forward code
print("Moving Forward...")
본 비슷한 질문을 내에서 유래하지만,그들은 don't 것을 내 질문에 대답이나 나는 할 수 없을 이해하는 대답이다. 할 수 있는 사람이 있 제공해 주십시오 나에게 간단한 방법으로 전화하이드 버튼을 클릭하 이벤트,그것을 주시면 감사하겠습니다.
다른 질문을 내가 보았다:
--https://stackoverflow.com/questions/30899484/python-flask-calling-functions-using-buttons
--https://stackoverflow.com/questions/40583347/calling-a-python-function-with-a-button
--https://stackoverflow.com/questions/21566649/flask-button-run-python-without-refreshing-page
당신은 단순히 이렇게의 도움으로 AJAX... 여기에 예를 호출하는 파이썬은 기능을 하는 인쇄 안녕하세요없는 리다이렉션하거나 페이지를 새로 고침.
에 app.py 을 넣어 아래 코드는 세그먼트입니다.
//rendering the HTML page which has the button
@app.route('/json')
def json():
return render_template('json.html')
//background process happening without any refreshing
@app.route('/background_process_test')
def background_process_test():
print "Hello"
return "nothing"
고 json.html 페이지 봐야 하는 다음과 같다.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type=text/javascript>
$(function() {
$('a#test').bind('click', function() {
$.getJSON('/background_process_test',
function(data) {
//do nothing
});
return false;
});
});
</script>
//button
<div class='container'>
<h3>Test</h3>
<form>
<a href=# id=test><button class='btn btn-default'>Test</button></a>
</form>
</div>
여기에 버튼을 누를 때 테스트는 간단하는 콘솔에서 당신이 볼 수 있"Hello" 를 표시하지 않고 어떤 상쾌합니다.
그것은 소리처럼 당신이 사용하려면이 웹 응용 프로그램으로 원격 제어를 위한 로봇,그리고 중핵 문제는 당신이't 원하는 페이지를 다시 모든 시간에 작업을 수행할 경우에,마지막 링크를 게시한 답변을 당신의 문제입니다.
나는 생각할 것은 오해에 대한 몇 가지 Flask. 한 한,당신이 할 수 있't 둥지에서 여러 기능이 단일 경로. You'다시 만들지 않는 설정의 기능에 대한 특정한 경로,당신은 당'다시 정의하는 하나의 특정한 것은 서버가 할 때에는 경로가 호출됩니다.
그 마음에,당신이 할 수있을 것이 문제를 해결하는 페이지로 리로드하여 변경 app.py 더 다음과 같다:
from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/forward/", methods=['POST'])
def move_forward():
#Moving forward code
forward_message = "Moving Forward..."
return render_template('index.html', forward_message=forward_message);
다음의 html,사용:
<form action="/forward/" method="post">
<button name="forwardBtn" type="submit">Forward</button>
</form>
...실행 당신의 앞으로 이동하는 코드입니다. 포함한다:
{{ forward_message }}
...당신이 원하는 앞으로 메시지가 표시될 수 있습니다 템플릿에.
이 원인이됩니다 당신의 페이지를 다시 로드하는 불가피를 사용하지 않고 AJAX Javascript.
index.html (index.html 해야에서는 템플릿 폴더)
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<h2>jQuery-AJAX in FLASK. Execute function on button click</h2>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
<script type=text/javascript> $(function() { $("#mybutton").click(function (event) { $.getJSON('/SomeFunction', { },
function(data) { }); return false; }); }); </script>
</head>
<body>
<input type = "button" id = "mybutton" value = "Click Here" />
</body>
</html>
test.py
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/SomeFunction')
def SomeFunction():
print('In SomeFunction')
return "Nothing"
if __name__ == '__main__':
app.run()