ajax 运行环境
- 需要运行在服务器上才能生效
- 作用: 提交异步请求,页面局部更新
- 应用场景:表单验证,页面上拉加载数据,数据分页,
ajxa 运行原理及实现
//创建ajax 对象
var xhr = new XMLHttpRequest();
//绑定ajax 请求地址和请求方法
xhr.open('get','http://www.baidu.com')
//发送请求
xhr.send()
// 获取相应数据
//1。 需要给xhr 绑定onload时间
xhr.onload = function () {
console.log(xhr.responseText)
}
ajax 服务器响应的数据
- 大多数情况下响应的是Json 数据(以django 为例)
服务器端:
#服务器 view 代码
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
# Create your views here
def index(request):
if request.method == 'POST':
return JsonResponse({'name':'liuy','sex':'nan','hobby':'watch'})
return render(request,'index.html')
前端:
var bar = document.getElementById('bar');
// console.log(bar);
bar.onclick= function () {
//创建ajax对象
var xhr = new XMLHttpRequest();
//请求地址
xhr.open('post','/index/');
//发送请求
xhr.send();
xhr.onload = function () {
var res = JSON.parse(xhr.response);
bar.innerText=res
}
};
请求参数传递
- get 请求 url 拼接
var xhr2 = new XMLHttpRequest();
var name = document.getElementById('uname').value;
var passwd = document.getElementById('passwd').value;
console.log(name,passwd,btn);
params = 'uname='+name+'&'+'passwd='+passwd
xhr2.open('get','/second/'+'?'+params);
xhr2.send();
- post请求 放入请求体中,同时设置请求头类型
var xhr = new XMLHttpRequest();
xhr.open('post','/second/'
//设置请求参数的类型
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// 发送post请求,form 类型
xhr.send('uname=test1&passwd=123456')
//xhr.setRequestHeader('Content-Type', 'application/json')
//json 转换成字符串
// var DataJson=Json.stringify({name:'xxx',age:30})
// 发送post请求,json 类型
//xhr.send(DataJson)
ajax 状态码
- 0 请求未建立
- 1 请求已建立,未发送
- 2 请求以发送
- 3 请求正在处理,未完成
- 4, 响应完成
xhr2.onreadyStateChange = function (){
xhr2.readyState;
};