Reputation: 55
This is simple if I was doing it in static html files, but as i'm working with Flask it is surprisingly difficult.
I have a html page which correctly includes a Javascript file. This java script files has an AJAX function that will read a textfile.
Does anyone know if I can reference a textfile in Javascript within a Python flask webapp?
HTML:
<script src="{{ url_for('static',filename='js/my.js') }}"></script>
JS:
function alertFunc() {
$.ajax({
url : "/Users/me/myfile.txt", //I believe this is the issue!
dataType: "text",
success : function (data) {
$("#div1").html(data);
}
});
I have put a test function in this JS file and it works so there is no issue with linking the HTML page with the JS page.
Upvotes: 1
Views: 1330
Reputation: 114038
add your .txt
file to your static folder
then point to /static/my.txt
or add an endpoint (@app.route('my_text.txt')
) and return it ...
its really easy... im not sure why you had the dig on flask ... I think its just as easy in flask as html and your powers in flask are much greater than simple html ...
main.py
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/')
def hello_world():
return render_template('index.html')
if __name__ == '__main__':
app.run()
static/main.js
function alertFunc() {
$.ajax({
url: "/static/my_text.txt",
dataType: "text",
success: function (data) {
console.log(data)
$("#div1").text(data);
}
});
}
static/my_text.txt
just a simple message
templates/index.html
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="/static/main.js"></script>
<div id="div1"></div>
<script>
alertFunc()
</script>
Upvotes: 2