需求:
flask中使用ajax 处理前端请求,每隔一段时间请求不通的接口,结果展示同一页面
用到 setTimeout方法,setTimeout(function(){},1000);setTimeout 中的 function 为第二次请求 就可以了
效果如图:请求了二个接口,间隔5秒,展示在同一页面
html:test.html
<html>
<head></head>
<body> <div class="header">
<h4>标题XXX</h4>
</div>
<div class="body">
<form class="form" method="post">
<br class="form-a"/>
<div class="form-b">
<label for="aaa"> XXX: <input class="form-control1" type="a" id="a"
name="a" maxlength="11"
placeholder="请输入XXX"/> </label>
</div>
<div class="box">
<label> XXXX: </label>
<label class="radio"> <input type="radio" id="b" name="b" value="0" checked=""/><span>b1</span> </label>
<label class="radio"> <input type="radio" id="b" name="b" value="1"/><span>b2</span> </label>
</div>
<br/>
<div class="form">
<button class="btn btn-primary" type="button" id="notify">查询</button>
</div>
</form>
</div> <div class="c" id="show2" style="display:none">
<div class="header">
<h4>结果:</h4>
</div>
<div class="body" id="show3">
</div>
</div>
<div class="body" id="show4">
</div>
</div>
</body>
// static 根据自己实际路径填写
<script type="text/javascript" src="static/js/main.min.js"></script>
<script type="text/javascript" src="static/js/jquery.min.js"></script> <script type="text/javascript"> // 消息提示
$('#notify').on('click', function () {
// ajax
var b = $("input[name='b']:checked").val();
var a = $("input[name='a']").val();
var data = {
data: JSON.stringify({
'b': b,
'a': a
}),
} if (a.length = 0) {
alert('XXXXX不能为空');
return;
}
$.ajax({
type: "POST",
dataType: "json",
url: "/test1",//调用后台test1方法
data: data,
success: function (result) {
console.log(result);
{
$('#show2').show() //此处展示
$("#show3").html(result) setTimeout(function () {
$.ajax({
type: "POST",
dataType: "json",
url: "/test2",//调用后台test2方法
data: data,
success: function (result) {
{# console.log('11111')#}
console.log(result);
{
$("#show4").html(result) }
},
error: function (result) {
{# console.log(result);//#}
{
alert(result);
}
}
});
},5000) // 间隔5秒 }
},
error: function (result) {
{# console.log(result);//#}
{
alert(result);
}
}
}); }) </script>
</html>
flask:
# 页面
@app.route('/test',methods=['GET','POST'])
def test():
return render_template("test/test.html") # test1
@app.route('/test112',methods=['GET','POST'])
def test112():
data = json.loads(request.form.get('data'))
b = data['b']
a = data['a']
res = b,a
return jsonify(res) # test2
@app.route('/test2',methods=['GET','POST'])
def test113():
data = json.loads(request.form.get('data'))
b = data['b']
a = data['a']
res = a
return jsonify(res)