Ajax学习笔记--- 【xmind 详细展示 浏览器与 服务器端通信,请求与响应报文】

php和express用来做后端,还是express强大和方便!!!

  • 翻看笔记才知道自己当时下载Fiddler,Wampserver,phpstudy_pro是为了什么,实在不敢说自己学过php

在这里插入图片描述

在这里插入图片描述

一、 Ajax介绍

  • HTTP
  • 原生,jQuery,fetch,axios
1-1 原生AJAX
  1. 简介: 全称为Asynchronous JavaScript And XML,就是异步的JS和XML
    • 通过AJAAX可以在浏览器中向服务器发送异步请求
    • 最大的优势: 无刷新获取数据
    • AJAX 不是新的编程语言,而是一种将现有的标准组合在一起使用的新方式
1-2 XML简介
    • XML可扩展标记语言
    • XML 被设计用来传输和存储数据
    • XML于HTML 类似,不同的是HTML中都是预定义标签,而XML中没有预定义标签
  1. XML 格式进行交换–> JSON
1-4 AJAX的特点
  1. 优点:
    • 可以无需刷新页面与服务器端进行通信
    • 允许根据用户事件来更新部分页面内容
  2. AJAX缺点
    • 没有浏览历史,不能回退
    • 存在跨域问题(同源)
    • SEO 不友好

第二章 HTTP+node

2-1 HTTP协议请求报文 与 响应文本结构
  1. HTTP : HTTP(hypertext transport protocol) 协议[超文本传输协议],,协议详细规定了浏览器和万维网服务器之间相互通信的规则.

    • 约定,规则

      2

      6

  2. 请求报文: 格式和参数

    POST /s?ie=utf-8 HTTP/1.1
    Host: atguigu.com
    Cookie:name=guigu
    Content-type:application/x-www-form-urlencoded
    User-Agent: chrome 83
    空行
    username=admin&password=admin
  3. 响应报文


    HTTP/1.1 200 ok
    Content-type:text/html;charset=utf-8
    Content-length:2048

    Content-encoding: gzip
    空行
2-2 Express框架介绍与基本使用
  1. npm init --yes
  2. npm i express
  3. node 脚本

第三章 AJAX

3-1 AJAX_GET
<!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 #90b;
        }
    </style>
</head>

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

    </div>
    <script>
        // 获取button元素
        const btn = document.getElementsByTagName('button')[0];
        // 绑定事件
        btn.onclick = function() {
            // 1. 创建对象
            const xhr = new XMLHttpRequest();
            // 2. 初始化设置请求方法和url
            // xhr.open('GET', 'http://localhost:8080/server');
            // 发送参数
            xhr.open('GET', 'http://localhost:8080/server?a=100&b=200&c=300');

            // 3. 发送
            xhr.send();
            // 4. 事件绑定 处理服务端返回的结果
            // on when  当..时候
            // resdystate 是 xhr 对象中的属性, 表示状态 0 1 2 3 4
            // change 改变
            xhr.onreadystatechange = function() {
                // 判断
                if (xhr.readyState === 4) {
                    // 判断响应状态码 200 404 403  401 500
                    // 2xx 成功
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // 处理结果  行   头  空行  体
                        // 1. 响应行
                        console.log(xhr.status); // 状态码
                        console.log(xhr.statusText); // 状态字符串
                        console.log(xhr.getAllResponseHeaders());
                        console.log(xhr.response); // 响应体

                        result.innerHTML = xhr.response;
                    }
                }
            }
        }
    </script>
</body>

</html>
3-2 AJAX_POST
<!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>
        #result {
            width: 200px;
            height: 100px;
            border: 1px solid #903;
        }
    </style>
</head>

<body>
    <div id="result"></div>
    <script>
        // 获取元素对象
        const result = document.getElementById("result");
        // 绑定事件
        result.addEventListener("mouseover", function() {
            // console.log("test");
            // 1. 创建对象
            const xhr = new XMLHttpRequest();
            // 2. 初始化 设置类型 与 URL
            xhr.open('POST', 'http://localhost:8080/server');
            // 3. 发送
            // xhr.send();
            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>
3-3 AJAX设置请求头信息
  1. 设置请求头

                // 设置请求头
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
                xhr.setRequestHeader('name', 'niutt');
    
  2. Content-Type: 设置请求体内容的类型

  3. 有效的bug

3-4 服务端响应JSON数据
3-4-1
3-5 nodemon自动重启工具

免去了不停重新启动node.js

3-6 IE缓存问题解决
  1. 对AJAX的请求结果缓存,再次请求时返回的是缓存数据,无法实时请求

  2. // ajax解决IE请求缓存问题
                xhr.open("GET", "http://localhost:8080/ie?t=+Date.now()");
    
3-7 Ajax请求超时与网络异常处理
  1. <button>点击发送请求</button>
        <div id="result"></div>
        <script>
            const btn = document.getElementsByTagName('button')[0];
            const result = document.querySelector('#result');
            btn.addEventListener('click', function() {
                const xhr = new XMLHttpRequest();
                // 超时设置 2s
                xhr.timeout = 2000;
                // 超时回调
                xhr.ontimeout = function() {
                        alert("网络异常,请稍后再试!");
                    }
                    // 网络异常的回调
                xhr.onerror = function() {
                    alert("你的网络似乎出了一些问题");
                }
    
                xhr.open("GET", 'http://localhost:8080/delay');
                xhr.send();
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4) {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            result.innerHTML = xhr.response;
                        }
                    }
                }
            })
        </script>
    
    
  2. image-20220103164837070

3-8 AJAX 请求重复发送问题
  1. 再次点击请求时,把第一个请求关闭
  2. 使用isSending来判断当前是否有正在发送的请求,有的话就abort,重新发送下一个请求

第四章 jQuery发送AJAX,Axios,fetch

4-1 jQuery中的AJAX
4-1-1 get请求,post请求
  1. $.get(url,[data],[calback],[type])

    • url: 请求的URL地址
    • data: 请求携带的参数
    • calback: 载入成功时回调函数
    • type: 设置返回内容格式,xml,html,script,json,text,_default
  2. <script>
           $('button').eq(0).click(function() {
               $.get("http://localhost:8080/jQuery-server", {
                   a: 100,
                   b: 200
               }, function(data) {
                   console.log(data);
               })
           })
           $('button').eq(1).click(function() {
               $.get("http://localhost:8080/jQuery-server", {
                   a: 100,
                   b: 200
               }, function(data) {
                   console.log(data);
               }, 'json')
           })
       </script>
    
4-1-2 jQuery通用方法发送AJAX请求
  1. 头信息实现有点问题,第22集
<script> 
$('button').eq(2).click(function() {
            $.ajax({
                // url
                url: 'http://localhost:8080/delay',
                // 参数
                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
                // }

            })
        })
    </script>
4-2 Axios发送AJAX请求
  1. 好处:
    • 在node.js发送http请求
    • 支持Promise
    • 拦截器机制
    • 数据请求
    • 自动返回json数据
  2. mdmdmdmmd,bugbugbugbug!!!
4-2-1 Axios 函数发送 AJAX请求
4-3 使用fetch函数发送AJAX请求

第五章 跨域

5-1同源策略
  1. 同源策略(Same-Origin Policy)最早由Netscape公司提出,是浏览器的一种安全策略
  2. 同源 : 协议,域名,端口号必须完全一致

image-20220117221351910

  1. 违背同源策略就是跨域
    • ajax默认遵守同源策略
  2. 同源策略就是来自同一区域
5-2 解决跨域
5-2-1 JSONP
  1. JSONP (JSON with Padding):是一个非官方的跨域解决方案,纯粹凭借程序员的聪明才智开发

    • 只支持get请求
  2. JSONP怎么工作:

    • 在网页有一些标签天生具有跨域能力,比如: img link iframe script
    • JSONP : 利用script标签的跨域能力来发送请求
  3. JSONP的使用:

    • 动态创建一个script标签

      var script  = document.createElement("script")
      
    • 设置script的scr, 设置回调函数

5-2-2 CORS(Cross-Origin Resource Sharing)
  1. 跨域资源共享,COPS是官方的跨域解决方案

    • 不需要客户端做任何特殊的操作,完全在服务器中进行处理,支持get和post请求,跨域资源共共享标准新增了一组HTTp首部字段
    • 允许服务器声明哪些源站通过浏览器有权限访问哪些资源
  2. CORS怎么工作

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值