[英]Open, edit and save a text file using XMLHttpRequest and javascript
[英]Open a text file with XMLHttpRequest() using ajax in Flask Python
我正在嘗試使用 Flask 中 W3school 的一個非常簡單的 ajax 示例和 Python。 該示例僅在按下按鈕時將一些數據從名為 ajax_info.txt 的文件加載到頁面。 我的桌面程序具有下一個簡化結構:
FlaskProject
app.py
-uploads
ajax_info.txt
-templates
html templates
我已使用下一個代碼將 ajax_info.txt 文件上傳到服務器。
def uploader_func():
if request.method == 'POST':
f = request.files['file']
file_path = os.path.join(app_config[UPLOAD_FOLDER], secure_filename(f.filename))
f.save(file_path)
#print(current_app.root_path)
#print(os.path.isfile(os.path.join(app_config.UPLOAD_FOLDER, secure_filename(f.filename))))
return 'file uploaded successfully'
這個 function 成功上傳文件並顯示它在本地上傳的位置,我也可以在上傳文件夾中看到它。 現在我必須用下一個腳本打開它:
<!DOCTYPE html>
<html>
<body>
<h1>The XMLHttpRequest Object</h1>
<p id="demo">Let AJAX change this text.</p>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("hi");
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "uploads/ajax_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
我已經嘗試了 URL 的所有可能組合來訪問 xhttp.open () function 中的文件,但沒有一個有效。 我收到錯誤net::ERR_ABORTED 404 (NOT FOUND)
我努力了:
我對如何訪問此文件感到困惑。 任何形式的幫助將不勝感激
您可以創建一個static
文件夾並將upload
文件夾放入其中。
static_folder (Optional[str]) – 在 static_url_path 提供的包含 static 文件的文件夾。 相對於應用程序 root_path 或絕對路徑。 默認為“靜態”。
https://flask.palletsprojects.com/en/2.0.x/api/
然后您可以在 Javascript 代碼中執行此操作:
xhttp.open("GET", "static/uploads/ajax_info.txt", true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.