Ajax详解(涵盖跨域问题解决)

一、什么是Ajax

  • ajax 全名 async javascript and XML
  • 是前后台交互的能力也就是我们客户端给服务端发送消息的工具,以及接受响应的工具
  • 是一个 默认异步执行机制的功能。

二、Ajax 的优势

  • 不需要插件的支持,原生 js 就可以使用
  • 用户体验好(不需要刷新页面就可以更新数据)
  • 减轻服务端和带宽的负担
  • 允许你根据用户事件来更新部分页面内容。

缺点:**

  • 搜索引擎的支持度不够,因为数据都不在页面上,搜索引擎搜索不到
  • 没有浏览历史,不能回退
  • 存在跨域问题(同源)

三、Ajax 的使用

  • 在 js 中有内置的构造函数来创建 ajax 对象
  • 创建 ajax 对象以后,我们就使用 ajax 对象的方法去发送请求和接受响应

3.1. 配置链接信息

const xhr = new XMLHttpRequest()
// xhr 对象中的 open 方法是来配置请求信息的
// 第一个参数是本次请求的请求方式 get / post / put / ...
// 第二个参数是本次请求的 url
// 第三个参数是本次请求是否异步,默认 true 表示异步,false 表示同步 默认是true
// xhr.open('请求方式', '请求地址', 是否异步)
xhr.open('get', './data.php',true)

上面的代码执行完毕以后,本次请求的基本配置信息就写完了

3.2. 发送请求

const xhr = new XMLHttpRequest()
xhr.open('get', './data.php', true)
// 使用 xhr 对象中的 send 方法来发送请求
xhr.send()

上面代码是把配置好信息的 ajax 对象发送到服务端

3.3. 一个基本的 Ajax 请求

一个最基本的 ajax 请求就是上面三步,但是光有上面的三个步骤,我们确实能把请求发送的到服务端,如果服务端正常的话,响应也能回到客户端,但是我们拿不到响应,如果想拿到响应,我们有两个前提条件:

  • 本次 HTTP 请求是成功的,也就是我们之前说的 http 状态码为 200 ~ 299
  • ajax 对象也有自己的状态码,用来表示本次 ajax 请求中各个阶段

3.4. Ajax状态码

ajax 状态码 xhr.readyState,是用来表示一个ajax请求的全部过程中的某一个状态

  • readyState === 0 : 表示未初始化完成,也就是 open 方法还没有执行
  • readyState === 1 : 表示配置信息已经完成,也就是执行完 open 之后
  • readyState === 2 : 表示 send 方法已经执行完成
  • readyState === 3 : 表示正在解析响应内容
  • readyState === 4 : 表示响应内容已经解析完毕,可以在客户端使用了

这个时候我们就会发现,当一个ajax请求的全部过程中,只有当readyState === 4的时候,我
们才可以正常使用服务端给我们的数据

所以,配合 http 状态码为 200 ~ 299

  • 一个 ajax 对象中有一个成员叫做 xhr.status
  • 这个成员就是记录本次请求的 http 状态码的

两个条件都满足的时候,才是本次请求正常完成

3.5. readyStateChange

  • ajax 对象中有一个事件,叫做 readyStateChange 事件
  • 这个事件是专门用来监听 ajax 对象的 readyState 值改变的的行为
  • 也就是说只要 readyState 的值发生变化了,那么就会触发该事件
  • 所以我们就在这个事件中来监听ajaxreadyState 是不是到 4
const xhr = new XMLHttpRequest()
xhr.open('get', './data.php')
xhr.send()
xhr.onreadyStateChange = function () {
   // 每次 readyState 改变的时候都会触发该事件
   // 我们就在这里判断 readyState 的值是不是到 4
   // 并且 http 的状态码是不是 200 ~ 299
   if (xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)) {
       // 这里表示验证通过
       // 我们就可以获取服务端给我们响应的内容了
   }
}    

3.6. responseText

  • ajax 对象中的responseText成员
  • 就是用来记录服务端给我们的响应体内容的
  • 所以我们就用这个成员来获取响应体内容就可以
const xhr = new XMLHttpRequest()
xhr.open('get', './data.php')
xhr.send()
xhr.onreadyStateChange = function () {
    // 每次 readyState 改变的时候都会触发该事件
    // 我们就在这里判断 readyState 的值是不是到 4
    // 并且 http 的状态码是不是 200 ~ 299
    if (xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)) {          
        // 我们在这里直接打印 xhr.responseText 来查看服务端给我们返回的内容
        console.log(xhr.responseText)
    }
}    

3.7. Ajax案例

<ul class="list">
  <li>
    <img src="" alt="" />
    <span></span>
  </li>
</ul>
<script>
  //创建一个Ajax对象
  const xhr = new XMLHttpRequest();
  //配置链接信息
  xhr.open("GET", "http://www.xiongmaoyouxuan.com:80/api/tabs");
  //发送请求
  xhr.send();
  //监听 ajax 对象的 readyState 值
  xhr.onreadystatechange = function () {
    //判断eadyState 的值是不是到 4
    // 并且 http 的状态码是不是 200 ~ 299
    if (xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)) {
      //获取服务端给我们的响应体内容,由于获取过来的是json字符串
      //所以我们要通过JSON.parse()转化为json对象
      let jsonData = JSON.parse(xhr.responseText);
      //调用渲染函数
      render(jsonData);
    }
  };
  //创建渲染函数页面
  function render(data) {
    //对数据进行解构赋值
    let {
      data: { list },
    } = data;
    //使用map映射到页面当中
    let lists = list.map(function (item) {
      return `
          <li>
              <img src="${item.imageUrl}" alt="">
              <span>${item.name}</span>
          </li>

          `;
    });
    //添加到ul里面
    document.querySelector(".list").innerHTML = lists.join("");
    //使用join()进行拼接
  }
</script>

四、使用 Ajax 发送请求时携带参数

  • 我们使用 ajax 发送请求也是可以携带参数的
  • 参数就是和后台交互的时候给他的一些信息
  • 但是携带参数 get 、 post、put、patch、delete这些方式还是有区别的。

4.1. 发送一个带有参数的GET请求

const xhr = new XMLHttpRequest()
xhr.open("GET", "http://localhost:3000/username?name=zwy&password=123")
//获取name等于zwy并且password等于123的数据
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)) {
        console.log(JSON.parse(xhr.responseText))
    }
}
xhr.send()

4.2. 发送一个带有参数的 POST 请求

如果是用 ajax 对象发送 post 请求,必须要先设置一下请求头中的 content-type,告诉一下服务端我给你的是一个什么样子的数据格式。

  • 如果是表单格式’key=value&key=value’则用application/x-www-form-urlencoded
  • 如果是json格式则用application/json
  • ajax的content-type默认值就是application/x-www-form-urlencoded;

4.2.1. 提交表单格式数据

const xhr = new XMLHttpRequest()
xhr.open("POST", "http://localhost:3000/username")
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)) {
        console.log(JSON.parse(xhr.responseText))
    }
}   
// ajax的content-type默认值就是application/x-www-form-urlencoded;
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
xhr.send(`name=张三&password=136`)

4.2.2. 提交json格式数据

const xhr = new XMLHttpRequest()
xhr.open("POST", " http://localhost:3000/username")
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)) {
        console.log(JSON.parse(xhr.responseText))
    }
}
xhr.setRequestHeader("Content-Type","application/json")
xhr.send(JSON.stringify({
    name:"ximen",
    password:"789"
}))

4.3. 发送一个PUT请求

put默认修改所有数据,如果send()传递的参数少于该对象的属性,则后面的会被默认删除。

const xhr = new XMLHttpRequest()
xhr.open("PUT", " http://localhost:3000/username/1")
//url地址后面必须指定修改哪个数据
// /1表示修改id为1的数据
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)) {
        console.log(JSON.parse(xhr.responseText))
    }
}
xhr.setRequestHeader("Content-Type","application/json") 
xhr.send(JSON.stringify({
    name:"张"
    //只传了一个属性,后面的password属性会被默认删除
}))

4.4. 发送一个PATCH请求

patch是部分修改,可以弥补put的缺陷。

const xhr = new XMLHttpRequest()
xhr.open("PATCH", " http://localhost:3000/username/1")
// url地址后面必须指定修改哪个数据
// 1表示修改id为1的数据
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)) {
        console.log(JSON.parse(xhr.responseText))
    }
}
xhr.setRequestHeader("Content-Type","application/json") 
xhr.send(JSON.stringify({
    name:"李四"
     // 只传了一个属性,后面的password属性会被保留,不做修改
}))

4.5. 发送一个DELETE请求

const xhr = new XMLHttpRequest()
xhr.open("DeLETE", " http://localhost:3000/username/1")
//指定你要删除id为几的数据
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)) {
        console.log(JSON.parse(xhr.responseText))
    }
}
xhr.send()

五、封装Ajax

如果页面中很多个请求,上面这种方法则需要new很多个XMLHttpRequest(),这样会使得代码有很多的重复,显然这样做是不合理的,所有我们需要封装一个Ajax来解决这个问题。

//如果data传入的是json格式,而header设置的是form表单编码
//我们就需要将json字符串进行转换。
function queryStringify(obj) {
    let str = ''
    for (let k in obj) str += `${k}=${obj[k]}&`
    //username=kerwin&password=789&
    return str.slice(0, -1)
}

// 封装 ajax
function ajax(options) {
    //设置一个options默认值,在我们不传递参数的时候默认是get提交
    let defaultoptions = {
        url: "",
        method: "GET",
        async: true,
        data: {},
        headers: {
            "content-type": "application/x-www-form-urlencoded"
        },
        success: function () { },
        error: function () { }
    }
    // 进行解构赋值
    let { url, method, async, data, headers, success, error } = {
    	//展开运算符
        ...defaultoptions,
        ...options
    }
    //判断headers的值是否为json
    if (typeof data === 'object' && headers["content-type"]?.indexOf("json") > -1) {
        data = JSON.stringify(data)
    }
    else {
        data = queryStringify(data)
    }
    // // 如果是 get 请求, 并且有参数, 那么直接组装一下 url 信息
    if (/^get$/i.test(method) && data) url += '?' + data

    // // 4. 发送请求
    const xhr = new XMLHttpRequest()
    xhr.open(method, url, async)
    xhr.onload = function () {
        if (!/^2\d{2}$/.test(xhr.status)) {
            // console.log(error)
            error(`错误状态码:${xhr.status}`) //回调
            return
        }

        // 执行解析
        try {
            let result = JSON.parse(xhr.responseText)
            success(result)
        } catch (err) {
            error('解析失败 ! 因为后端返回的结果不是 json 格式字符串')
        }
    }


    // // 设置请求头内的信息
    for (let k in headers) xhr.setRequestHeader(k, headers[k])
    //判断method是不是get
    if (/^get$/i.test(method)) {
        xhr.send()
    } else {
        xhr.send(data)
    }
}

六、解决ie缓存问题

问题: 在一些浏览器中(IE),由于缓存机制的存在,ajax 只会发送的第一次请求,剩余多次请求不会再发送给浏览器而是直接加载缓存中的数据。

解决方式: 浏览器的缓存是根据url地址来记录的,所以我们只需要修改url地址 即可避免缓存问题

xhr.open("get", "/testAJAX?t=" + Date.now());

七、请求超时与网络异常

当你的请求时间过长,或者无网络时,进行的相应处理

const xhr = new XMLHttpRequest();
//超时设置 2s 设置
xhr.timeout = 2000;
//超时回调
xhr.ontimeout = function () {
  alert("网络异常, 请稍后重试!!");
};
//网络异常回调
xhr.onerror = function () {
  alert("你的网络似乎出了一些问题!");
};

xhr.open("GET", "http://127.0.0.1:8000/delay");
xhr.send();
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    if (xhr.status >= 200 && xhr.status < 300) {
      result.innerHTML = xhr.response;
    }
  }
};

八、取消请求

在请求发出去后但是未响应完成时可以进行取消请求操作

x = new XMLHttpRequest();
x.open("GET",'http://127.0.0.1:8000/delay');
x.send();
x.abort(); // abort方法可以取消请求

九、重复请求问题

利用七中取消请求知识点,当我点击时,判断之前请求是否在发送中,如果是,则停止请求

//判断标识变量
if(isSending) x.abort();// 如果正在发送, 则取消该请求, 创建一个新的请求
x = new XMLHttpRequest();
//修改 标识变量的值
isSending = true;
x.open("GET",'http://127.0.0.1:8000/delay');
x.send();
x.onreadystatechange = function(){
    if(x.readyState === 4){
        //修改标识变量
        isSending = false;
    }
}

十、常见三种Ajax请求方式

10.1. jQuery发送AJAX请求

10.1.1. $.get()

$.get(
  "http://127.0.0.1:8000/jquery-server",
  { a: 100, b: 200 },
  function (data) {
    console.log(data);
  },
  "json"
);

10.1.2. $.post()

$.post(
  "http://127.0.0.1:8000/jquery-server",
  { a: 100, b: 200 },
  function (data) {
    console.log(data);
  }
);

10.1.3. $.ajax

$.ajax({
  //url
  url: "http://127.0.0.1:8000/jquery-server",
  //参数
  data: { a: 100, b: 200 },
  //请求类型
  type: "GET",
  //响应体结果
  dataType: "json",
  //成功的回调
  success: function (data) {
    console.log(data);
  },
  //超时时间
  timeout: 2000,
  //失败的回调
  error: function () {
    console.log("出错啦!!");
  },
  //头信息
  headers: {
    c: 300,
    d: 400,
  },
});

10.2. Axios发送AJAX请求

10.2.1. axios.get()

//GET 请求
axios
  .get("/axios-server", {
    //url 参数
    params: {
      id: 100,
      vip: 7,
    },
    //请求头信息
    headers: {
      name: "aodi",
      age: 20,
    },
  })
  .then((value) => {
    console.log(value);
  });

10.2.2. axios.post()

axios.post(
   "/axios-server",
   {
     username: "admin",
     password: "admin",
   },
   {
     //url
     params: {
       id: 200,
       vip: 9,
     },
     //请求头参数
     headers: {
       height: 180,
       weight: 180,
     },
   }
 );

10.2.3. axios()

axios({
  //请求方法
  method: "POST",
  //url
  url: "/axios-server",
  //url参数
  params: {
    vip: 10,
    level: 30,
  },
  //头信息,此部分如果使用自定义的头信息,需要服务端进行相应修改,正常不设置
  headers: {
    a: 100,
    b: 200,
  },
  //请求体参数
  data: {
    username: "admin",
    password: "admin",
  },
}).then((response) => {
  //响应状态码
  console.log(response.status);
  //响应状态字符串
  console.log(response.statusText);
  //响应头信息
  console.log(response.headers);
  //响应体
  console.log(response.data);
});

10.3. Fetch发送AJAX请求

fetch("http://127.0.0.1:8000/fetch-server?vip=10", {
  //请求方法
  method: "POST",
  //请求头
  headers: {
    name: "aodi",
  },
  //请求体
  body: "username=admin&password=admin",
})
  .then((response) => {
    // return response.text();
    return response.json();
  })
  .then((response) => {
    console.log(response);
  });

十一、9种常见的跨域解决方案(详解)

https://blog.csdn.net/qq_44741577/article/details/136534161?spm=1001.2014.3001.5501

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值