老师,你好,麻烦帮我解答一下哈
为什么我打开网页的时候默认打开的就是03文件中的数据,然后输入再url网址里输入/state的时候才会进行跳转。
2.在视频中老师只讲了关于状态码这一部分,状态值视频里好像没有讲到。
3.代码的运行原理不是特别明白。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>04.Ajax中state的使用</title>
</head>
<body>
<h1>04.Ajax中state的使用</h1>
<input type="button" name="" id="" value="获取数据" onclick="submitFrom()"/>
<script type="text/javascript">
function submitFrom(){
//创建Ajax对象
var xhr=new XMLHttpRequest();
url='/state'
//请求方式(告诉Ajax以什么样的 方式 发送请求给 谁)
xhr.open('POST',url)
//发送请求
xhr.send()
//处理数据
xhr.onreadystatechange=function(){
//console.log(xhr.readyState) //在控制台输出 获取 Ajax 状态码
//if(xhr.readyState==4 && xhr.status==200){ /*当状态码==4并且状态值为200时*/
//console.log(xhr.status)
if(xhr.readyState ==4){ /*当状态码==4状态值为200时*/
if(xhr.status ==200){ /*状态值为200时*/
console.log(xhr.responseText) /*则获取服务器端给客户端的响应数据*/
console.log(JSON.parse(xhr.responseText)) //将 json 字符串转换为 json 对象
}else{console.log(xhr.status)}
}
}
}
</script>
</body>
</html>
from flask import Flask,request,render_template
app=Flask(__name__) #创建Flask服务器应用对象
@app.route('/login',methods=['GET','POST']) #发送/login请求地址,可支持get,post参数传递
def login():
if request.method =="GET":
return 'get请求成功'
elif request.method =="POST":
return 'post请求成功'
#@app.route('/') #不写参数默认get请求
def text(): #render_template返回的是一套html的模板数据
return render_template('03.Ajax中post参数传递.html') #传递数据给Flask服务器接收.
@app.route('/state',methods=["GET",'POST']) #接收/state请求
def state():
if request.method =="GET":
return render_template('04.Ajax中state的使用.html')
elif request.method =="POST":
#return 'post请求成功'
return '{"name":"吕小布","age":10}'
if __name__=="__main__":
app.run(debug=True)