原生Ajax:

  • Ajax简介:

Ajax全称:Asynchronous JavaScript And XML,就是异步的JS和XML

通过Ajax可以在浏览器中向服务器发送异步请求,最大的优势:无刷新获取数据

Ajax不是新的编程语言,而是一种将现有的标准组合在一起使用的新方式

  • XML简介:

XML可扩展标记语言

XML被设计用来传输的存储数据

XML和HTML类似,不同的是HTML中都是预定义标签,而XML中没有预定义标签,全都是自定义标签,用来表示一些数据

目前XML已经被JSON取代

Ajax的特点:

  • Ajax的优点:

1)无需刷新页面而与服务器进行通信

2)允许你根据用户事件来更新部分页面内容

  • Ajax的缺点

1)没有浏览历史,不能回退

2)存在跨域问题(同源)

3)SEO不友好

HTTP:

  • HTTP(hypertext transport protocol):

超文本传输协议, 协议详细规定了浏览器和万维网服务器之间互相通信的规则

  • 请求报文

行:请求类型(POST) / 请求地址(?ie=utf-8) / HTTP协议版本

头:Host: atguigu.com

​ Cookie: name=guigu

​ Content-type: application/x-www-form-urlencoded

​ User-Agent: chrome 83

空行:

体:username=admin&password=admin

  • 响应报文

行:HTTP/1.1 200 OK

头:Content-Type: text/html;charset=utf-8

​ Content-length: 2048

​ Content-encoding: gzip

空行:

体:<html>

​ <head></head>

​ <body>

​ <h1>尚硅谷</h1>

​ </body>

​ </html>

查看请求和响应报文

Request Headers:请求行和请求头内容

Query String Parameters:对URL进行解析之后的结果

Response Headers:响应行和响应头

Response:响应体

GET请求:

get.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Ajax GET</title>
  <style>
    #result {
      width: 200px;
      height: 100px;
      border: 1px solid red;
    }
  </style>
</head>

<body>
  <button>点击发送请求</button>
  <div id="result"></div>
</body>

<script>
  // 获取button
  const btn = document.getElementsByTagName('button')[0];
  const result = document.getElementById('result');
  btn.onclick = function () {
    // 创建对象
    const xhr = new XMLHttpRequest();
    // 初始化,设置请求方法和url
    xhr.open('GET', 'http://127.0.0.1:8000/server?a=100&b=200&c=300');
    // 发送
    xhr.send();
    // 事件绑定,处理服务端返回的结果
    xhr.onreadystatechange = function () {
      // 判断(服务端返回了所有结果)
      if (xhr.readyState === 4) {
        // 判断响应状态码 200 404
        if (xhr.status >= 200 && xhr.status < 300) {
          // 处理结果 行 头 空行 体
          // console.log(xhr.status);//状态码
          // console.log(xhr.statusText);//状态字符串
          // console.log(xhr.getAllResponseHeaders());//所有响应头
          // console.log(xhr.response);//响应体
          result.innerHTML = xhr.response;
        } else {

        }
      }
    }
  }
</script>

</html>

server.js

// 引入express
const express = require("express");

// 创建应用对象
const app = express();

// 创建路由规则
// request是对请求报文的封装
// response是对响应报文的封装
app.get("/server", (request, response) => {
  // 设置响应头 设置允许跨域
  response.setHeader("Access-Control-Allow-Origin", "*");
  // 设置响应体
  response.send("HELLO Ajax GET");
});

// 监听端口启动服务
app.listen(8000, () => {
  console.log("服务已经启动,8000端口监听中");
});

POST请求:

POST.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Ajax POST</title>
  <style>
    #result {
      width: 200px;
      height: 100px;
      border: 1px solid red;
    }
  </style>
</head>

<body>
  <div id="result"></div>

  <script>
    const result = document.getElementById('result');
    result.addEventListener("mouseover", function () {
      // 绑定事件
      const xhr = new XMLHttpRequest();
      // 初始化 设置类型 url
      xhr.open('POST', 'http://127.0.0.1:8000/server');
      // 设置请求头
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xhr.setRequestHeader('name', 'application/x-www-form-urlencoded');
      // 发送
      xhr.send('a=100&b=200&c=300');
      // 事件绑定
      xhr.onreadystatechange = function () {
        // 判断
        if (xhr.readyState === 4) {
          if (xhr.status > - 200 && xhr.status < 300) {
            result.innerHTML = xhr.response;
          }
        }
      }
    })
  </script>
</body>

</html>

server.js

// 引入express
const express = require("express");

// 创建应用对象
const app = express();

// 创建路由规则
// request是对请求报文的封装
// response是对响应报文的封装

app.post("/server", (request, response) => {
  // 设置响应头 设置允许跨域
  response.setHeader("Access-Control-Allow-Origin", "*");
  // 响应头自定义
  response.setHeader("Access-Control-Allow-Headers", "*");
  // 设置响应体
  response.send("HELLO Ajax POST");
});

// 监听端口启动服务
app.listen(8000, () => {
  console.log("服务已经启动,8000端口监听中");
});

请求JSON数据:

JSON.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>JSON</title>
  <style>
    #result {
      width: 200px;
      height: 100px;
      border: 1px solid red;
    }
  </style>
</head>

<body>
  <div id="result"></div>

  <script>
    const result = document.getElementById('result');
    window.onkeydown = function () {
      const xhr = new XMLHttpRequest();
      xhr.responseType = 'json';
      xhr.open('GET', 'http://127.0.0.1:8000/json-server');
      xhr.send();
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            // console.log(xhr.response);
            // result.innerHTML = xhr.response;
            // 手动对数据转化
            // let data = JSON.parse(xhr.response);
            // console.log(data);
            result.innerHTML = xhr.response.name;
          }
        }
      }
    }
  </script>
</body>

</html>

server.js

// 引入express
const express = require("express");

// 创建应用对象
const app = express();

// 创建路由规则
// request是对请求报文的封装
// response是对响应报文的封装

app.all("/json-server", (request, response) => {
  // 设置响应头 设置允许跨域
  response.setHeader("Access-Control-Allow-Origin", "*");
  // 响应头自定义
  response.setHeader("Access-Control-Allow-Headers", "*");

  // 响应一个数据
  const data = {
    name: "wss",
  };
  // 对对象进行字符串转换
  let str = JSON.stringify(data);
  // 设置响应体
  response.send(str);
});

// 监听端口启动服务
app.listen(8000, () => {
  console.log("服务已经启动,8000端口监听中");
});

请求超时和网络异常的处理:

index.html

// 超时设置
      xhr.timeout = 2000;
      // 超时回调
      xhr.ontimeout = function () {
        alert('网络异常,稍后重试')
      }
      // 网络异常回调
      xhr.onerror = function () {
        alert('网络貌似出现了问题')
      }

Ajax取消请求:

let x = null;
x = new XMLHttpRequest();
//取消请求
x.abort();

重复请求问题:

let isSending = false;//是否正在发送Ajax请求
btn.onclick = function() {
    if(isSending) x.abort();
    x = new XMLHttpRequest();
    isSending = true;
    x.open('GET','URL');
    x.send();
    x.onreadystatechange = function() {
        if(x.readState === 4) {
            isSending = false;
        }
    }
}

jQuery发送请求:

  • GET:
$('btn').click(function() {
    $.get('url',{a:10, b:20}, function(data) {
        console.log(data)
    },'json')
})
  • POST
$('btn').click(function() {
    $.post('url',{a:10, b:20}, function(data) {
        console.log(data)
    })
})
  • 通用方法:
$('btn').click(function() {
    $.ajax({
        url: 'url',
        data: {a:10, b:20},
        type: 'GET',
        dataType: 'json',
        success: function(data) {
            console.log(data);
        },
        //头信息设置
        headers: {
            name : 值
        }
    })
})

axios:

GET或POST

  <script>
    const btns = document.querySelectorAll('button');
    // 配置baseURL
    axios.defaults.baseURL = 'url';
    btn[0].onclick = function () {
      // GET请求
      axios.get('/路径', {
        // url 参数
        params: {
          id: 100,
          vip: 1
        },
        // 请求头信息
        headers: {
          name: 'name',
          age: 20
        }
      }).then(value => {
        console.log(value);//返回的是对象
      });
    }
  </script>

通用方式

  <script>
    const btns = document.querySelectorAll('button');
    btn[1].onclick = function () {
      axios({
          //请求方法
        methods: 'HET'
          url: 'url',
          params: {
              a: 10,
              b: 20
          },
          //头信息
          headers: {
              a: 1,
              b: 2
          },
          //请求体参数
          data: {
              name: 'name'
          }
      }).then(response => {
          console.log(response);
      })
    }
  </script>
最后修改:2023 年 04 月 18 日 10 : 30 AM
如果觉得我的文章对你有用,请随意赞赏