ajax调用接口步骤(ajax调用后端接口实例)

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)
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至624739273@qq.com举报,一经查实,本站将立刻删除。
Like (0)
柳的头像

相关推荐

发表回复

Please Login to Comment
微信
微信
SHARE
TOP
要想花得少,就用购宝。话费电费9折起,官方公众号:购宝