ajax

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;
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值