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)