0

I'm implementing autocomplete with Flask and JavaScript, and I'm trying to put the JavaScript in a different file. My folder structure is like:

- Project
    - static
    |   -js
    |      autocomplete.js
    - templates
    |   index.html  
    main.py

If I add the script in index.html:

<script>
$(function() {
    $.ajax({
        url: '{{ url_for("autocomplete") }}'
    }).done(function (data) {
         $('#inputBox').autocomplete({
             source: data,
             minLength: 1
         });
    });
});
</script>

It works fine, but when I put the code into /static/js/autocomplete.js and add <script src="../static/js/autocomplete.js"></script> in index.html, I get a 404:

127.0.0.1 - - [11/Oct/2017 07:54:10] "GET /%7B%7B%20url_for(%22static%22,%22autocomplete%22)%20%7D%7D HTTP/1.1" 404 -

So how I should write the path in url_for()?

davidism
  • 121,510
  • 29
  • 395
  • 339
Jie Hu
  • 87
  • 2
  • 9
  • The python code has a line like: @app.route('/autocomplete',methods=['GET']). I'm not calling the js from python, but oppositely. – Jie Hu Oct 11 '17 at 04:07

2 Answers2

2
{{ url_for('static', filename='js/autocomplete') }}
1

You'll find what you need here: http://flask.pocoo.org/docs/quickstart/#static-files

Basically you just need a "static" folder at the root of your package, and then you can use url_for('static', filename='js/autocomplete.js') or directly link to your files with http://example.com/static/js/autocomplete.js

Gui
  • 763
  • 1
  • 7
  • 20
  • Tnx for the answer, but your example is calling js in python code. I want to call python method in js. – Jie Hu Oct 11 '17 at 04:06
  • You cannot call python methods within javascript. If you want to call a url from flask, do you need to create a route for this url and call that route. – Gui Oct 11 '17 at 04:09
  • Sorry, for some misunderstanding. If I put the above javascript in my index.html with then it works perfectly. But if I put the script in individual file in /static/js/autocomplete.js and in index.html I use it returns 404. can not find path autocomplete ... – Jie Hu Oct 11 '17 at 04:43
  • I made mistake, sorry. After check the document I was able to add include to reach the url. Thanks – Jie Hu Oct 11 '17 at 17:01