简体   繁体   中英

Flask - Javascript requests not working? 404 NOT FOUND

So I'm migrating from apache to using flask, I've moved all my css, javascript, csv and Images to static. From there I've spent a while changing all the hrefs so everything loads correctly.
Everything the html is loading is working fine, but all of the requests javascript is sending are 404'ing and I'm not sure why.

My directory structure is as follows:
Python:
------- static:
--------------- css:
--------------- csv:
------------------------gamesToday.csv
--------------- js:
--------------- Images:
------------------------logo.png
------------------------logo-small.png
------- templates:
------------------main.html
-------flaskTest.py
My flasktest.py simply loads and renders the main.html file at the moment.

Javascript request for csv file:

$.ajax({
    type: "GET",
    url: "{{url_for('static', filename='csv/gamesToday.csv')}}",
    dataType: "text",
    success: function(data) {processData(data);}
 });

Javascript for loading image:

function logoSizing(){
    if($(window).width() < 992)
        $("#logo").attr("src", "{{url_for('static', filename='Images/small-logo.png");
    else
        $("#logo").attr("src", "{{url_for('static', filename='Images/logo.png");
}

The strange thing is when i move the request for the image into html the image loads correctly, so I know that the file is infact there, so I presume the error is in the fact I can't make an AJAX call like this? If so, how do I go about making it correctly?

Apologies if this is very simple, just started learning flask today and I'm having serious trouble wrapping my head around it.

.js files are not parsed by the jinja template engine so it wont replace {{url for...}} with the actual url.

you will need to pass the url in from one of your html templates or hardcode the path

for js files:

{{url_for('static',filename='main.js')}}

for images files:

{{url_for('static',filename='main.js')}}

example:(adding script in html file)

<script src="{{url_for('static',filename='main.js')}}"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM