Rac*_*mon 5 html javascript python flask
我有一个 Flask 应用程序,它有一个页面,用户可以在其中输入一个句子。我想将这个用户输入输入到一个 Flask 方法中,该方法将对那个句子执行一些计算,然后返回结果(这是一个字符串)。
理想情况下,我希望它返回到同一页面,就在表单的提交按钮下方。
目前,我正在尝试使用 javascript 来做到这一点。这是我目前所拥有的:
结果.html
<head>
<script type=text/javascript>
$(function() {
$('a#test').bind('click', function() {
$.getJSON('/result_sentence',{
sentence: $('textarea[name="sentence"]').val()}, function(data) {
// do nothing
document.getElementById('display').innerHTML = data.result;
});
return false;
});
</script>
</head><body>
<!-- The form where the user inputs -->
<div id="interactive" style="margin-top:50px">
<textarea style="width:100%;" rows="3" name="sentence" placeholder="Enter your sentence"></textarea>
<a href="#" id=test button type="submit" class="btn btn-lg btn-success"> Predict </a>
<label> I predict.. </label>
<p><span id='display'></span></p>
</div>
Run Code Online (Sandbox Code Playgroud)
应用程序
@app.route('/result_sentence')
def result_sentence():
sentence = flask.request.args.get('sentence')
pred = getPrediction(sentence)
return jsonify(result=pred)
Run Code Online (Sandbox Code Playgroud)
另外,应该注意的是,在 results.html 上,我已经调用了另一个 Flask 函数,该函数将我的 Flask 应用程序重定向到 results.html 并显示了一些图表。
所以我面临的主要问题是我不确定为什么当我点击按钮时没有任何反应。在我看来,当单击按钮时,它应该将句子传递给 Flask 函数并执行计算。我查看了已经在 StackOverflow 上发布的一堆问题,例如:Flask - 在按钮 OnClick 事件上调用 python 函数, 但它们在这方面并没有真正帮助我。我真的不知道哪里出了问题,所以我很感激任何见解或帮助。
谢谢!
编辑: 所以似乎第一个问题是单击按钮时根本不会调用 JS 函数...
You need to use $.ajax with jquery. First, simply create an input box and button which, when clicked, will trigger the script to call the Ajax. In the HTML, the javascript will retrieve the user's input when the button is clicked, and the input will be sent to the flask route:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<input type='text' id='word'>
<button type='button' id ='retrieve'>Submit</button>
<div id='wordResult'></div>
</body>
<script>
$(document).ready(function() {
$('#retrieve').click(function(){
var word = $('#word').val();
$.ajax({
url: "/get_word",
type: "get",
data: {word: word},
success: function(response) {
$("#wordResult").html(response.html);
},
error: function(xhr) {
//Do Something to handle error
}
});
});
});
</script>
</html>
Run Code Online (Sandbox Code Playgroud)
Then, create the route in app.py:
@app.route('/get_word')
def get_prediction():
word = flask.request.args.get('word')
return flask.jsonify({'html':getPrediction(word)})
Run Code Online (Sandbox Code Playgroud)