1.
2.ajax对象 发送请求等...
//创建请求对象 const xhr=new XMLHttpRequest() //初始化 设置请求方法 和 url xhr.open('GET','http://127.0.0.1:5000/student?a=200&b=300')
//设置请求头 一般放身份校验等信息 传给服务器
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
//f发送
xhr.send('a=123&b=321')//当为post的时候发送该数据
xhr.responseType='json'//自动转换格式
// readystate是xhr的对象属性 值为0,1,2,3,4 4代表完全返回相应数据
xhr.onreadystatechange=function () {
if (xhr.readyState===4){
if (xhr.status>=200 && xhr.status<300){
console.log(xhr.status)
console.log(xhr.statusText)
console.log(xhr.getAllResponseHeaders())
console.log(xhr.response)
// const data=JSON.parse(xhr.response)//手动转换
// for (let i=0;i<data.length;i++){
// $('div').html(data[i].name)
// }
//配置了自动转换后
$('div').html(xhr.response[0].name)
}
}
}
3.Jquery发ajax请求
$(function () {
$('button:eq(0)').click(function () {//get请求
$.get('http://127.0.0.1:5000/student',{a:100,b:200},function (data) {
console.log(data) //发get请求
},'json')//第四个参数是返回数据为指定类型
})
$('button:eq(1)').click(function () {//post请求
$.post('http://127.0.0.1:5000/student',{a:100,b:200},function (data) {
console.log(data) //发get请求
}) //发post请求
})
$('button:eq(2)').click(function () {
$.ajax({//ajax请求
url:'http://127.0.0.1:5000/student',
type:'GET',
data:{
a:100,
b:200
},
success:function (data) {
console.log(data)
},
error:function (data) {
console.log(data)
}
})
})//发ajax请求
})
4.axios发get post ajax请求
$('button:eq(0)').click(function () {
axios.get('http://127.0.0.1:5000/student',{
params:{
vip:666
},
headers: {
name: 'atguigu'
},
data:{
name:'xjw',
password:'1223'
}
}).then(value => console.log(value))//value是包含data,headers,request等数据的服务器返回对象
})
//post方法同理
$('button:eq(1)').click(function () {
axios.post('http://127.0.0.1:5000/student', {//第二部分是请求体,第三部分是配置信息 而不是像get方法那样第二部分是配置信息。
name: 'xjw',
password: '1223'
},
{
params: {
vip: 666
},
headers: {
name: 'atguigu'
},
}).then(value => console.log(value))
})//value是包含data,headers,request等数据的服务器返回对象
$('button:eq(2)').click(function () { //发ajax请求。
axios({
type:'post',
// url:'..........',
params:{
vip:666
},
headers: {
name: 'atguigu'
},
data:{
//请求体
}
}).then(response => console.log(response))//value是包含data,headers,request等数据的服务器返回对象
})