使用JS发送GET请求并显示结果

时间:2020-11-06 23:25:53

标签: javascript python

当我单击网页上的按钮时,我想发送一个HTTP GET请求,然后在页面上显示结果。

我的html按钮和段落:

<input type="button" id='testButton' value="TEST" onclick=test()>
<p id="test">paragraphe test</p>

我的js函数test():

function test() {
document.getElementById("test").innerHTML = httpGet("http://127.0.0.1:5000/hello_world");}

我的httpGet()函数:

function httpGet (url) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", url, true);
xmlHttp.send();
return xmlHttp.responseText.responseText; }

还有我简单的HTTP请求处理程序(在python中带有flask):

#Run the server
from flask import Flask, request
from flask_defs import get_username

app = Flask(__name__)

@app.route('/hello_world', methods=['GET'])
def hello():
    print('Hello, World!')
    return 'Hello, World!'

if __name__ == "__main__":
    app.run(debug=True)

我可以在python控制台中看到请求已被接收,但是在页面上显示“未定义”

编辑:我已经尝试过一个w3schools来等待响应:

<!DOCTYPE html>
<html>
<body>

<h2>The XMLHttpRequest Object</h2>

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "http://127.0.0.1:5000/hello_world", true); #I also tried with false
  xhttp.send();
}
</script>

</body>
</html>

我也在同步模式下尝试过

xmlHttp.open( "GET", url, false)

请保持温柔,我是Web开发人员和js的新手:)

编辑2: 错误是“原因:CORS标头'Access-Control-Allow-Origin'丢失” 因此,我需要在烧瓶响应中添加此标头,但我无法使其正常工作……某些机构可以向我解释该怎么做吗?

1 个答案:

答案 0 :(得分:0)

所以问题是我没有响应标头“ Access-Control-Allow-Origin” 我通过以下方式更改了我的烧瓶获取处理程序:

@app.route('/hello_world', methods=['GET'])
def hello():
    print('Hello, World!')
    response = flask.make_response('Hello, World!',200)
    response.mimetype = "text/plain"
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response

我也使用了同步模式:

xmlHttp.open( "GET", url, false);