ajax入门笔记

1.1 Ajax的特点

	Ajax的优点: 
	  ①可以无需刷新页面与服务器进行通信
	  ② 允许根据用户事件来更新部分页面内容
	Ajax的缺点:
	  ① 没有浏览历史,不可回退
	  ② 存在同源跨域问题
	  ③ SEO(搜索引擎优化)不友好(不容易被网络爬虫爬取)

1.2 HTTP协议

**HTTP (hypertext transport protocol)协议 超文本传输协议,详细规定了浏览器和万维网服务器之间的互相通信的规则。**
HTTP请求报文:
① 行       GET、POST...方法   / url   HTTP/1.1(协议版本)
②头         Host: 
③空行
④体

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

响应报文
行  HTTP/1.1         200     OK
头
       
空行
体

Express服务端框架基本使用

使用的IDE是vscode
全局 安装express框架(需要有node环境)安装在当前目录下
在这里插入图片描述
安装express的命令

npm install express
配置服务端文件 server.js
// 1. 引入express
const express = require('express');

// 2. 创建express对象

const app = express()

// 3. 创建路由规则
app.get('/server', (request, response) => {
  // 设置响应头 设置允许跨域
  response.setHeader('Access-Control-Allow-Origin', '*')
  // 设置响应体
  response.send('Hello Ajax GET');
})

app.get('/ie', (request, response) => {
  // 设置响应头 设置允许跨域
  response.setHeader('Access-Control-Allow-Origin', '*')
  // 设置响应体
  response.send('Hello IE 2');
})

app.all('/server', (request, response) => {
  // 设置响应头 设置允许跨域
  response.setHeader('Access-Control-Allow-Origin', '*')
  // 响应头
  response.setHeader('Access-Control-Allow-Headers', '*')
  // 设置响应体
  response.send('HELLO AJAX POST')
})

app.all('/json-server', (request, response) => {
  // 设置响应头 设置允许跨域
  response.setHeader('Access-Control-Allow-Origin', '*')
  // 响应头
  response.setHeader('Access-Control-Allow-Headers', '*')
  // 响应一个数据
  const data = {
    name: 'tom'
  };
  // 对对象进行字符串转换
  let str = JSON.stringify(data);
  // 设置响应体
  response.send(str)
})
// 4. 监听端口启动服务
app.listen(8000, () => {
  console.log('服务已经启动, 8000端口监听中')
})

启动服务
在server.js文件所在位置输入

 node server.js

在这里插入图片描述

请求的基本配置

<!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>POST 请求</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    #result {
      width: 200px;
      height: 200px;
      border: 1px solid #903;
    }
  </style>
</head>
<body>
  <div id="result"></div>
  <script>
    // 获取元素对象
    const result = document.querySelector("#result");
    // 绑定事件
    result.addEventListener("mouseover", function() {
      // 1. 创建对象
      const xhr = new XMLHttpRequest();
      // 2. 初始化 设置类型与 URL
      xhr.open('POST', 'http://127.0.0.1:8000/server');
      // 设置请求头
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
      xhr.setRequestHeader('name', 'tom')
      // 3. 发送
      // xhr.send('a=100&b=200&c=300');
      xhr.send('a=100&b=200&c=300')
      // 4. 事件绑定
      xhr.onreadystatechange = function(){
        // 判断
        if (xhr.readyState === 4 ) {
          if (xhr.status >= 200 && xhr.status < 300) {
            // 处理服务器返回的结果
            result.innerHTML = xhr.response;
          }
        }
      }
    })
  </script>
</body>
</html>
json数据自动转化
<!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>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    #result {
      width: 200px;
      height: 200px;
      border: 1px solid orange;
    }
  </style>
</head>

<body>
  <div id="result"></div>
  <script>
    const result = document.querySelector("#result");
    window.addEventListener('keydown', function () {
      // 发送请求
      const xhr = new XMLHttpRequest();
      //
      // 设置响应体数据的类型
      xhr.responseType = 'json';
      xhr.open('GET', 'http://127.0.0.1:8000/json-server')
      // 发送
      xhr.send()
      // 事件绑定
      xhr.addEventListener('readystatechange', 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);
            // console.log(data.name);
            console.log(xhr.response);
            // 自动转换
            result.innerHTML = xhr.response.name;
          }
        }
      })
    })
  </script>
</body>

</html>

IE缓存问题
<!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>IE 缓存问题</title>
  <style>
    #result {
      width: 200px;
      height: 200px;
      border: 1px solid #258;
    }
  </style>
</head>
<body>
  <button>点击发送请求</button>
  <div id="result"></div>
  <script>
    let btn = document.querySelector('button');
    let result = document.querySelector('#result');

    btn.addEventListener("click", function() {
      // 创建对象
      const xhr = new XMLHttpRequest();
      // 2.
      // IE 缓存 ajax 解决方法
      xhr.open('GET', 'http://127.0.0.1:8000/ie?t=' + Date.now())
      xhr.send();
      xhr.addEventListener('readystatechange', function() {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            result.innerHTML = xhr.response;
          }
        }
      })
    })
  </script>
</body>
</html>
Ajax超时请求与网络异常处理
<!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>延时请求</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    #result {
      width: 200px;
      height: 200px;
      border: 2px solid orange;
    }
  </style>
</head>
<body>
  <button>点击发送请求</button>
  <div id="result"></div>
  <script>
    let btn = document.querySelector('button');
    let result = document.querySelector('#result');
    btn.addEventListener('click', function() {
      const xhr = new XMLHttpRequest();
      // 超时设置 2s
      xhr.timeout = 2000;
      // 超时回调
      xhr.addEventListener('timeout', function() {
        alert('网络异常');
      })

      xhr.open('GET', 'http://127.0.0.1:8000/delay')
      xhr.send()
      xhr.addEventListener('readystatechange', function() {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            result.innerHTML = xhr.response;
          }
        }
      })
    })
  </script>
</body>
</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>延时请求</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
    #result {
      width: 200px;
      height: 200px;
      border: 2px solid orange;
    }
  </style>
</head>
<body>
  <button>点击发送请求</button>
  <div id="result"></div>
  <script>
    let btn = document.querySelector('button');
    let result = document.querySelector('#result');
    btn.addEventListener('click', function() {
      const xhr = new XMLHttpRequest();
	  // 网络异常事件 error
      xhr.addEventListener('error', function() {
        alert('网络异常')
      })
      xhr.open('GET', 'http://127.0.0.1:8000/delay')
      xhr.send()
      xhr.addEventListener('readystatechange', function() {
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 300) {
            result.innerHTML = xhr.response;
          }
        }
      })
    })
  </script>
</body>
</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>Document</title>
  <style>

  </style>
</head>
<body>
  <button>点击发送</button>
  <button>点击取消</button>
  <script>
    
    let btns = document.querySelectorAll('button');
    let x = null;
    btns[0].onclick = function() {
      x = new XMLHttpRequest();
      x.open('GET', 'http://127.0.0.1:8000/delay');
      x.send();
    }

    // abort
    btns[1].addEventListener('click', function() {
      x.abort();
    })
  </script>
</body>
</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>重复发送问题</title>
</head>
<body>
  <button>点击发送</button>
  <script>
    // 获取元素对象
    let x = null
    let isSending = false; // 是否正在发送AJAX请求
    const btn = document.querySelector('button');
    btn.addEventListener('click', function() {
      // 判断标识符变量
      if (isSending) x.abort() // 如果正在发送,则取消请求,创建一个新的请求
      x = new XMLHttpRequest();
      // 修改标识变量值
      isSending = true
      x.open('GET', 'http://127.0.0.1:8000/delay')
      x.send()
      x.addEventListener('readystatechange', function() {
        if (x.readyState === 4) {
          // 修改标识变量
          isSending = false
          if (x.status >= 200 && x < 300) {
            console.log(x.response)
          }
        }
      })
    })
  </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值