【发布时间】:2021-08-08 13:23:23
【问题描述】:
我正在尝试在 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'
这个函数成功上传文件并显示它在本地上传的位置,我也可以在uploads文件夹中看到它。现在我必须用下一个脚本打开它:
<!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 () 函数中的文件,但没有一个有效。我收到错误 net::ERR_ABORTED 404 (NOT FOUND)
我试过了:
- http://127.0.0.1:5000/uploads/ajax_info.txt、http://127.0.0.1:5000/ajax_info.txt 等 URL 和完整路径的组合。
- 我用这个文件的路径打印了 os.path.isfile() 并检查了它是否存在。
- 在 xamp 服务器上尝试了相同的代码,它运行良好。
我对如何访问此文件感到困惑。任何形式的帮助将不胜感激
【问题讨论】:
标签: javascript python ajax flask xmlhttprequest