老师,html中18行的拼接,params+atr为什么代表的是传参中的key,options.data[atr]就代表的是值呢
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>07.Ajax中封装传参</title>
</head>
<body>
<h1>07.Ajax中封装传参</h1>
<hr>
<input type="button" value="测试get参数" onclick="test1()">
<input type="button" value="测试post参数" onclick="test2()">
<script>
//定义封装
function ajax(options){ //options接收参数
var xhr=new XMLHttpRequest() //创建一个Ajax对象
var params=''
for(var atr in options.data){
params=params + atr + "=" + options.data[atr]+"&"
}
params=params.substr(0,params.length-1) //从0开始,截取到最后一位-1
//get 请求
if(options.type =='get') {
options.url = options.url + '?' + params
}
xhr.open(options.type,options.url) //传入一个get和post请求类型,地址
//post 请求
if(options.type=='post'){
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded') //以表单的方式进行传递数据
xhr.send(params) //发送请求
}else{
xhr.send() //发送请求(get的情况下)
}
xhr.onreadystatechange=function (){ //处理数据
if(xhr.readyState ==4 && xhr.status ==200){ /*当状态码==4并且状态值为200时*/
console.log(xhr.responseText) /*则获取服务器端给客户端的响应数据*/
}
}
}
//调用Ajax
function test1(){
ajax({
type:'get',
url:'/login',
data:{'name':'吕小布','pwd':123}
})
}
function test2(){
ajax({
type:'post',
url:'/login',
data:{'name':'吕小布','pwd':123}
})
}
</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}'
@app.route('/asynca') #接收/asynca请求
def asynca ():
return render_template('05.Ajax中的同步与异步的使用.html')
@app.route('/fz01')
def fz01():
return render_template('06.Ajax中的简单封装.html')
@app.route('/fz02')
def fz02():
return render_template('07.Ajax中封装传参.html')
if __name__=="__main__":
app.run(debug=True)