【问题标题】:Open a text file with XMLHttpRequest() using ajax in Flask Python在 Flask Python 中使用 ajax 使用 XMLHttpRequest() 打开一个文本文件
【发布时间】: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)

我试过了:

我对如何访问此文件感到困惑。任何形式的帮助将不胜感激

【问题讨论】:

    标签: javascript python ajax flask xmlhttprequest


    【解决方案1】:

    您可以创建一个static 文件夹并将upload 文件夹放入其中。

    static_folder (Optional[str]) – 在 static_url_path 提供静态文件的文件夹。相对于应用程序 root_path 或绝对路径。默认为“静态”。

    https://flask.palletsprojects.com/en/2.0.x/api/

    然后你可以在你的 Javascript 代码中做到这一点:

    xhttp.open("GET", "static/uploads/ajax_info.txt", true);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 2015-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-20
      • 2022-03-28
      相关资源
      最近更新 更多