Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm learning AJAX according to MDN tutorial, but when I try the first sample to fetch test.html, local server always response with 404, no matter I use absolute or relative path. I have read other similar questions in stackoverflow, but none of them can solve my problem.

Here is my directory structure and source code:

|--templates
|  |--index.html
|  |--test.html
|
|--app.py

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>index</title>
  </head>
  <body>
    <button id="ajaxButton" type="button">Make a request</button>
    <script>
      (function(){
          let httpRequest
          document.getElementById("ajaxButton").addEventListener('click', makeRequest)

          function makeRequest() {
              httpRequest = new XMLHttpRequest()

              if (!httpRequest) {
                  alert('Giving up: can not create an XMLHTTP instance')
                  return false
              }

              httpRequest.onreadystatechange = alertContents
              httpRequest.open('GET', 'test.html', true)
              httpRequest.send()
          }

          function alertContents() {
            if (httpRequest.readyState === XMLHttpRequest.DONE) {
                if (httpRequest.status === 200) {
                    alert(httpRequest.responseText)
                }else {
                    alert('There was a problem with the request.')
                }
            }
          }
      })();
    </script>
  </body>
</html>
question from:https://stackoverflow.com/questions/65857224/xmlhttprequest-open-url-cant-access-the-file-i-request-for

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
229 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're trying to do requests to test.html, but that route does not exist, you have only defined the / route in your Python code which renders index.html template.

If you want the user to access arbitrary templates (e.g. 127.0.0.1:5000/templates/my-template.html), you can write the following route:

@app.route('/templates/<template_name>')
def view_template(template_name):
    return render_template(template_name)

Once you've defined that route, the request to /templates/test.html should be successful:

httpRequest.open('GET', '/templates/test.html', true)

Flask looks for the specified template in templates folder by default when you call render_template.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...