Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

javascript - XMLHttpRequest.open url can't access the file I request for

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...