ajax调用接口并显示返回参数

前端需要调用接口并返回结果时,可以使用ajax来实现。菜鸡程序员对其中的原理不是很了解,但是看网上很多教程很麻烦,这里贴一个我成功实现的一个case。

  • 使用id来定位需要修改的部分
  • 点击按钮时触发loaddoc()函数
  • 使用console.log(‘error’)可以在控制台打出想看的东西
  • xhttp.open(“post”, “http://localhost:5000/users/xxxxx/me”, true);使用post向接口发送请求,true表示异步请求
  • xhttp.setrequestheader(‘content-type’, ‘application/json’);设置请求的header
  • xhttp.send(json.stringify(senddata));将变量json格式化后传输
  • xhttp.onreadystatechange = function()在这里执行想要进行的html变换的操作,json.parse(xhttp.responsetext)
<!doctype html>
<html>
<body>

<h1>xmlhttprequest target</h1>

<button type="button" onclick="loaddoc()">request data</button>

<p>suggestion: <span id="demo"> </span></p>

<script>
function loaddoc() {
  console.log('error');
  var xhttp = new xmlhttprequest();
  xhttp.open("post", "http://localhost:5000/users/xxxxx/me", true);
  xhttp.setrequestheader('content-type', 'application/json');
  var senddata = {"abc":123};
  //将用户输入值序列化成字符串
  xhttp.send(json.stringify(senddata));
  xhttp.onreadystatechange = function() {
    if (xhttp.readystate == 4) {
        var jsonobj = json.parse(xhttp.responsetext);
        document.getelementbyid("demo").innerhtml = jsonobj.data.adjustperiod
        console.log(jsonobj.data.adjustperiod);
    }
  }
}

</script>

</body>
</html>

ajax跨域问题解决

python中,在flask创建app实例时,添加如下代码即可:

from flask_cors import cors
# 创建app实例对象
    app = flask(__name__)
    cors(app)