AJAX

首先我们要知道什么是ajax?
ajax就是在不刷新页面的情况下,发送http请求,接收到服务器给客户端的数据。ajax的全称:async javascript and XML,是一个异步执行的和后台交互的技术。( ajax可同步可异步)
比如我们上网浏览的邮箱注册或者分页等,都是使用了不刷新页面便发送了ajax请求。

ajax的书写
1.首先创建ajax对象

var xhr = new XMLHttpRequest();//但是这个写法是兼容性的,在ie下不能兼容

兼容写法

 var xhr = new ActiveXObject("Microsoft.XMLHTTP");
 //兼容ie678
 var xhr = new ActiveXObject("Msxml2.XMLHTTP");
 //更低版本ie
var xhr;
    try {
        // 针对W3C标准浏览器的
        xhr = new XMLHttpRequest();
    } catch (e) {
        // 针对低版本IE的
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }

2.建立http请求

xhr.open(“请求方式”,“请求地址”,true)
第三个参数:true代表异步请求,false代表同步请求
第三个参数可省略,默认情况下是异步操作

var xhr = new XMLHttpRequest();
xhr.open("get/post","demo.php",true)

3.监听ajax的请求状态
onreadystatechange=>是ajax状态改变事件
readyState是ajax对象请求的状态:
0:未初始化,对象已经建立,但是还未初始化,就是还未调用send方法

​1:已经初始化,但是还没有调用send方法

2:发送数据,send方法已经调用,但是http头未知

3:数据接收中,已经接收部分数据,因为响应以及http头不全,这是通过responseText获取少部分数据会出现错误

4:请求完成,数据接收完毕,此时可以通过responseText获取完整的相应数据

responseText是接收服务器响应的字符串数据,如果是xml数据使用responseXML来接收,如果是json数据,其实也是使用字符串形式相应回来的,使用responseText接收以后,使用JSON.parse(str)或str.parseJSON()转为json对象处理

 xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
         if (xhr.status >= 200 && xhr.status < 300) {
             var res = xhr.responseText;// 从服务器返回的文本信息
            }
        }
    }

如果是同步请求,就必须将send方法放到监听状态的后面,因为同步就是按顺序执行,先发送请求,当监听到状态的时候,已经发送成功了,所以打印的代码并没有执行(先监听状态,再发送请求)

4.发送请求

xhr.send()

如果post请求要加上下面这一行,如果是是get请求直接xhr.send()即可

 xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xhr.send(=) //发送请求携带数据,设置数据格式:键=值

get和post的区别:

  1. get请求的数据展示在地址栏,post在http请求的请求主体中
  2. get请求的数据长度有限制,post没有限制,除非在服务器设置限制
  3. get请求的数据格式有限制,必须是url编码的,post的数据没有限制
  4. get请求不如post安全
  5. get请求容易有缓存,post没有缓存

get请求

 var box = document.querySelector("#box");
    var btn = document.querySelector("#btn");
    btn.onclick = function() {
             var xhr = new XMLHttpRequest();
             xhr.open("get", "demo.php");
             xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                  if (xhr.status >= 200 && xhr.status < 300){
                    var res = xhr.responseText;
                     console.log(res)
                    box.innerHTML = res;
                    }
                }
           }
          
             xhr.send();
        }

post请求

var box = document.querySelector("#box");
    var btn = document.querySelector("#btn");
    btn.onclick = function() {
             var xhr = new XMLHttpRequest();
             xhr.open("post", "demo.php");
             xhr.onreadystatechange = function() {
                if (xhr.readyState === 4) {
                  if (xhr.status >= 200 && xhr.status < 300){
                    var res = xhr.responseText;
                     console.log(res)
                    box.innerHTML = res;
                    }
                }
           }
             xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
             xhr.send();
        }

可封装通用的ajax

function createAjax(obj) {
    // var xhr = new XMLHttpRequest();
    if (obj.dataType == undefined) {
        obj.dataType = "json";
    }
    if (obj.dataType != "json" && obj.dataType != "string") {
        throw new Error("传入的数据类型必须是json或者string类型");
    }
    if (obj.url == undefined) {
        throw new Error("url不能为空");
    }
    if (Object.prototype.toString.call(obj.url) != "[object String]") {
        throw new Error("请求的url不是正确的url");
    }
    //是否传入了请求方式
    if (obj.type === undefined) {
        obj.type = "get"
    }
    if (obj.type != "get" && obj.type != "post") {
        throw new Error("请求方式必须是get或者post");
    }

    if (obj.data != undefined) {
        if (Object.prototype.toString.call(obj.data) == '[object String]' && obj.data.indexOf("=") != -1) {
            obj.data = obj.data;
        } else if (Object.prototype.toString.call(obj.data) == "[object Object]") {
            var arr = [];
            for (var attr in obj.data) {
                arr.push(attr + "=" + obj.data[attr])
            }
            var data = arr.join("&");
            obj.data = data;
        } else {
            throw new Error("传入的数据类型不对,只接受字符串和对象类型");
        }

    if (obj.type == "get") {
        obj.url = "?" + obj.data
    }
    if (obj.async == undefined) {
        obj.async = true;
    }
    if (Object.prototype.toString.call(obj.async) != "[object Boolean]") {
        throw new Error("异步参数必须是个布尔值");
    }
    //判断是否传入了obj.success和obj.fail
    if (obj.success == undefined) {
        obj.success = function() {

        }
    }
    if (obj.fail == undefined) {
        obj.fail = function() {

        }
    }
    var xhr;
    try {
        // 针对W3C标准浏览器的
        xhr = new XMLHttpRequest();
    } catch (e) {
        // 针对低版本IE的
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhr.open(obj.type, obj.url, obj.async);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
                res = xhr.responseText;
                if (obj.dataType === "json") {
                    res = JSON.parse(res)
                }
                obj.success(res)
            } else {
                obj.fail()
            }
        }

    }
    if (obj.type === "post") {
        xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        if (obj.data != undefined) {
            xhr.send(obj.data);
            return
        }
    }
    xhr.send();
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值