I'm trying to make the jQuery UI autocomplete widget work with the Flask framework.
http://flask.pocoo.org/docs/patterns/jquery/
http://jqueryui.com/autocomplete/#remote
This is my HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0.1//EN" "http://w3.org/TR/html4/strict.dtd">
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script type=text/javascript>
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
</script>
<style>
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
</style>
<script type="text/javascript">
$(function() {
$( "#university" ).autocomplete({
source: $.getJSON($SCRIPT_ROOT + "/_search_university",
{search: $('input[name="university"]').val()}),
minLength: 2,
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="university">University: </label>
<input id="university", name="university" />
</div>
</body>
And this is my Flask method:
@app.route('/_search_university')
def search_university():
search = request.args.get('search')
results = session.query(University).filter(name.like('%' + search + '%')).all()
return jsonify(results)
I think I got it right but it doesn't seem to work. As soon as I reload the page the function is called (even without input and with the minLength = 2), looks for the universities but displays nothing (even when he found the universities).
After the first look-up (right after the page) loads, the widget stops sending requests to the server if when I type more then 2 letters in the field.
Can somebody help me here? I'm just trying to get the most basic usage of the autocomplete widget with AJAX by using Flask.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…