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)

原创文章,作者:投稿专员,如若转载,请注明出处:https://www.506064.com/n/209170.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
投稿专员的头像投稿专员
上一篇 2024-12-08 15:25
下一篇 2024-12-08 15:25

相关推荐

发表回复

登录后才能评论