• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Ajaxajax 基本使用 / 跨域问题 / get和post

武飞扬头像
one or only
帮助1

目录

1、Ajax 概述

1.1 AJAX 简介

1.2 XML 简介

1.3 AJAX 的特点

1.3.1 AJAX 的优点

1.3.2 AJAX 的缺点

2、AJAX 的使用

2.1 使用步骤

2.2 完整 get 请求 带参数(会手写)

2.3 完整 post 请求 带参数(会手写)

2.4 解析 json 数据

2.5 解构赋值连续写法(补充)

2.6 IE 缓存问题 (时间戳)

2.7 ajax 请求的异常与超时处理

2.8 ajax 取消请求 xhr.abort( )

2.9 避免多次重复请求

3、jQuery封装Ajax

4、跨域

4.1 JSONP 解决跨域(工作不用,面试常问)(手写)

4.2 jQuery 封装 JSONP

4.3 CORS 解决跨域(后端技术)

5、get 和 post

GET

POST

1.Ajax 概述

1.1 AJAX 简介

AJAX 全称为 Asynchronous JavaScript And XML,就是异步的 JS 和 XML。

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

大白话:有时候不想页面抖动和跳转,不刷新页面就可以刷新新的数据,是前后端最常用的交互方式

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

1.2 XML 简介

XML 可扩展标记语言(Extensible Markup Language)

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

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

比如说我有一个学生数据:
name = “孙悟空” ; age = 18 ; gender = “男” ;
用 XML 表示:

  1.  
    <student>
  2.  
    <name>孙悟空</name>
  3.  
    <age>18</age>
  4.  
    <gender></gender>
  5.  
    </student>
  6.  
     

现在已经被 JSON 取代了:

  1.  
    {"name":"孙悟空","age":18,"gender":"男"}
  2.  
     

1.3 AJAX 的特点

1.3.1 AJAX 的优点

① 可以无需刷新页面而与服务器端进行通信
② 允许你根据用户事件来更新部分页面内容

1.3.2 AJAX 的缺点

没有浏览历史,不能回退(只有一个页面)
存在跨域问题 (同源) 很重要,如何解决跨域
SEO 不友好(搜索引擎,爬虫爬不到 ajax 更新的东西)

2. AJAX 的使用

2.1 使用步骤

核心对象

XMLHttpRequest
AJAX 所有操作都是通过该对象进行的

使用步骤

  1. 初始化环境, 下载 express 包
  1.  
    # npm init --yes 初始化
  2.  
    # npm i express 安装express

学新通

  1. 编写 js 代码 server.js
  1.  
    // 1. 引入express
  2.  
    const express = require('express');
  3.  
     
  4.  
    // 2. 创建应用对象
  5.  
    const app = express();
  6.  
     
  7.  
    // 2.1暴露静态资源
  8.  
    app.use(express.static(__dirname '/src'))
  9.  
    // 3. 创建路由规则
  10.  
    // request 是对请求报文的封装
  11.  
    // response 是对响应报文的封装
  12.  
    app.get('/test_get', (request, response) => {
  13.  
    // 设置响应
  14.  
    console.log("有人请求test_get了");
  15.  
    response.send("Hello_test_get");
  16.  
    });
  17.  
     
  18.  
    // 4. 监听端口,启动服务
  19.  
    app.listen(8000, () => {
  20.  
    console.log("服务已经启动,测试地址如下:");
  21.  
    console.log("http://127.0.0.1:8080/1_ajax小试牛刀.html");
  22.  
    })
  23.  
     
学新通
  1. 运行 server.js
node server.js
  1. 安装 nodemon, 可以自动重启服务器
# npm install -g nodemon

启动服务

# ndoemon server.js

1、ajax 小试牛刀. html

  1.  
    <!DOCTYPE html>
  2.  
    <html lang="en">
  3.  
    <head>
  4.  
    <meta charset="UTF-8">
  5.  
    <meta >
  6.  
    <title>AJAX GET 请求</title>
  7.  
    <style>
  8.  
    #result{
  9.  
    width: 200px;
  10.  
    height: 100px;
  11.  
    border: solid 1px #90b;
  12.  
    }
  13.  
    </style>
  14.  
    </head>
  15.  
    <body>
  16.  
    <button>点击发送请求</button>
  17.  
    <div id="result"></div>
  18.  
    <script>
  19.  
    //获取button元素
  20.  
    const btn = document.getElementsByTagName('button')[0];
  21.  
    const result = document.getElementById('result');
  22.  
    btn.onclick = function(){
  23.  
    //1.创建xhr的实例对象
  24.  
    const xhr = new XMLHttpRequest();
  25.  
    //2.指定发送请求方法method和url
  26.  
    xhr.open('GET','http://127.0.0.1:8080/test_get');
  27.  
    //3.发送请求
  28.  
    xhr.send();
  29.  
    //4.事件绑定 处理服务端返回的结果
  30.  
    // 当 准备 状态 发生变化
  31.  
    xhr.onreadystatechange = function(){
  32.  
    /* if(xhr.readyState ===1){
  33.  
    xhr.setRequestHeader('demo',123)//配置请求头
  34.  
    }*/
  35.  
    /* if(xhr.readyState ===2){
  36.  
    xhr.setRequestHeader('demo',123)//配置请求头--报错(send已经调用了,已经无法修改请求头)
  37.  
    }*/
  38.  
    /* if(xhr.readyState ===3){
  39.  
    console.log('3时接收到的数据',xhr.response);//小的数据已经回来了
  40.  
    console.log('3时接收到的响应头',xhr.getAllResponseHeaders());//所有响应头
  41.  
     
  42.  
    }*/
  43.  
    if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300)){
  44.  
    // 处理 行 头 空行 体
  45.  
    //响应行
  46.  
    // console.log(xhr.status);//http的状态码
  47.  
    // console.log(xhr.statusText);//状态字符串
  48.  
    // console.log(xhr.getAllResponseHeaders());//所有响应头
  49.  
    console.log(xhr.response);//返回的数据
  50.  
    //设置result的文本
  51.  
    result.innerHTML = xhr.response;
  52.  
    }
  53.  
    }
  54.  
    }
  55.  
    </script>
  56.  
    </body>
  57.  
    </html>
  58.  
     
  59.  
     
学新通

readystate 是 xhr 对象中的属性,有 5 种状态 0,1,2,3,4,变化 4 次 (了解即可)

    0: 实例出来的那一刻就是0,初始状态
    1: 服务器连接已建立,(open已经调用,但是send还没有调用,此时可以修改请求头内容)
    2: 请求已接收(send已经调用了,已经无法修改请求头
    3: 请求处理中 (已经回来一部分数据,小的数据已经在此阶段接受完毕,较大的数据等待进一步的接收)
    4: 请求已完成,且响应已就绪(数据全部接受完毕

2.2 完整 get 请求 带参数(会手写)

server.js

  1.  
    const express = require('express');
  2.  
    const app = express();
  3.  
    app.use(express.static(__dirname '/src'))
  4.  
    // 响应GET请求 #
  5.  
    app.get('/test_get', (request, response) => {
  6.  
    console.log("有人请求test_get了,携带的query参数是:",request.query);
  7.  
    response.send("Hello_test_get");
  8.  
    });
  9.  
    // 响应GET请求 #2
  10.  
    app.get('/test_get2/:name/:age', (request, response) => {
  11.  
    console.log("有人请求test_get2了,携带的params参数是:",request.qparams);
  12.  
    response.send("Hello_test_get2");
  13.  
    });
  14.  
    app.listen(8000, () => {
  15.  
    console.log("服务已经启动,测试地址如下:");
  16.  
    console.log("http://127.0.0.1:8080/3_ajax——get请求.html");
  17.  
    })
  18.  
     
学新通

3、ajax——get 请求. html (面试需完整手写)

  1.  
    btn.onclick = function(){
  2.  
    const xhr = new XMLHttpRequest();
  3.  
    xhr.onreadystatechange = function(){
  4.  
    if(xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)){
  5.  
    console.log(xhr.response);//返回的数据
  6.  
    }
  7.  
    }
  8.  
    /*
  9.  
    需要掌握(query和params的形式)
  10.  
    1.形如:key=value&key=value 就是query参数的 urlencoded 编码形式
  11.  
    2.形如:/xx/xxx/ 老刘/18 就是params参数
  12.  
    */
  13.  
    //2.指定发送请求方法method和url
  14.  
    xhr.open('GET','http://127.0.0.1:8080/test_get?name=老刘&age=18'); //携带query参数,使用urlencoder编码
  15.  
    //xhr.open('GET','http://127.0.0.1:8080/test_get2/老刘/18'); //携带params参数
  16.  
    //3.发送请求
  17.  
    xhr.send();
  18.  
    }
  19.  
     
学新通

2.3 完整 post 请求 带参数(会手写)

学新通

server.js

  1.  
    const express = require('express');
  2.  
    const app = express();
  3.  
     
  4.  
    //使用中间件解析urlencoded编码形式的请求体参数
  5.  
    //app.use(express.urlencoded({extended:true}))
  6.  
     
  7.  
    //使用中间件解析json编码形式的请求体参数
  8.  
    app.use(express.json())
  9.  
     
  10.  
    app.use(express.static(__dirname '/src'))
  11.  
     
  12.  
    // 响应POST请求
  13.  
    /* post方式可以接收query和params参数(但一般不这么用)
  14.  
    app.post('/test_post/:name/:age',(request,response)=>{
  15.  
    console.log("有人请求test_post了",request.params);
  16.  
    response.send("Hello_test_post");
  17.  
    });
  18.  
    */
  19.  
     
  20.  
    //post方式的接收请求体参数
  21.  
    app.post('/test_post/:name/:age',(request,response)=>{
  22.  
    console.log("有人请求test_post了",request.body);
  23.  
    response.send("Hello_test_post");
  24.  
    });
  25.  
     
  26.  
    app.listen(8000, () => {
  27.  
    console.log("服务已经启动,测试地址如下:");
  28.  
    console.log("http://127.0.0.1:8080/4_ajax——post请求.html");
  29.  
    })
  30.  
     
学新通

4、ajax——post 请求 (面试需完整手写)

  1.  
    btn.onclick = function(){
  2.  
    // 1
  3.  
    const xhr = new XMLHttpRequest();
  4.  
    xhr.onreadystatechange = function(){
  5.  
    if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300)){
  6.  
    console.log(xhr.response);//返回的数据
  7.  
    }
  8.  
    }
  9.  
    /* post 可以带query和params参数,但是很少用
  10.  
    // 1 xhr.open('POST','http://127.0.0.1:8080/test_post?name=老刘&age=18');
  11.  
    // 2 xhr.open('POST','http://127.0.0.1:8080/test_post/老刘/18'); //携带params参数
  12.  
    xhr.send();
  13.  
    */
  14.  
    // 2 指定发送请求的:method、url、参数
  15.  
    xhr.open('POST','http://127.0.0.1:8080/test_post')
  16.  
     
  17.  
    // 追加请求响应头用于识别携带的请求体参数的编码形式-urlencoded
  18.  
    // xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  19.  
     
  20.  
    // 追加请求响应头用于识别携带的请求体参数的编码形式-json
  21.  
    xhr.setRequestHeader('Content-Type','application/json');
  22.  
     
  23.  
    // 3 发送请求
  24.  
    // 携带urlencoded编码形式的请求体参数
  25.  
    //xhr.send(name=老刘&age=18);
  26.  
     
  27.  
    // 携带json编码形式的请求体参数
  28.  
    const person = {name:'老刘'age:18}
  29.  
    xhr.send(JSON.stringify(person));
  30.  
    }
  31.  
     
学新通

2.4 解析 json 数据

server.js

  1.  
    const express = require('express');
  2.  
    const app = express();
  3.  
     
  4.  
    app.use(express.static(__dirname '/src'))
  5.  
     
  6.  
    //post方式的接收请求体参数
  7.  
    app.get('/get_person',(request,response)=>{
  8.  
    console.log("有人请求get_person了");
  9.  
    const person ={name:'老刘',age:18,sex='女'}
  10.  
    response.send(JSON.stringify(person))
  11.  
    });
  12.  
    app.listen(8000, () => {
  13.  
    console.log("服务已经启动,测试地址如下:");
  14.  
    console.log("http://127.0.0.1:8080/5_ajax_解析json数据.html");
  15.  
    })
  16.  
     
学新通

5、ajax_解析 json 数据. html

  1.  
    btn.onclick = function(){
  2.  
    // 1
  3.  
    const xhr = new XMLHttpRequest();
  4.  
    xhr.onreadystatechange = function(){
  5.  
    if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300)){
  6.  
    console.log(xhr.response);//返回的数据
  7.  
    }
  8.  
    /* 手动解析json
  9.  
    const {name,age,sex}= JSON.parse(xhr.response);//返回的数据 解构赋值
  10.  
    */
  11.  
    const {name,age,sex} = xhr.response;
  12.  
    content.innerHTML=(`
  13.  
    <ul>
  14.  
    <li>姓名:${name}</li>
  15.  
    <li>年龄:${age}</li>
  16.  
    <li>性别:${sex}</li>
  17.  
    </ul>`)
  18.  
    }
  19.  
     
  20.  
    // 2 指定发送请求的:method、url、参数
  21.  
    xhr.open('GET','http://127.0.0.1:8080/get_person')
  22.  
     
  23.  
    // responseType用于指定返回数据的格式
  24.  
    xhr.responseType='json'
  25.  
     
  26.  
    // 3 发送请求
  27.  
    xhr.send();
  28.  
     
  29.  
    }
  30.  
     
学新通

2.5 解构赋值连续写法(补充)

  1.  
    let obj= {a:1,b:{c:2}}
  2.  
    //标准解构赋值
  3.  
    const {c} = obj.b
  4.  
    //连续解构赋值
  5.  
    const {b:{c}}=obj
  6.  
    console.log(c);
  7.  
    //连续解构赋值 重命名
  8.  
    const {b:{c:value}}=obj
  9.  
    console.log(alue);
  10.  
     

2.6 IE 缓存问题 (时间戳)

状态码 304 是服务器请求过了

server.js

  1.  
    const express = require('express');
  2.  
    const app = express();
  3.  
     
  4.  
    app.use(express.static(__dirname '/src'))
  5.  
    // 响应GET请求
  6.  
    app.get('/get_person',(request,response)=>{
  7.  
    console.log("有人请求get_person了");
  8.  
    const person ={name:'海峰',age:18,sex='女'}
  9.  
    response.send(JSON.stringify(person))
  10.  
    });
  11.  
    app.listen(8000, () => {
  12.  
    console.log("服务已经启动,测试地址如下:");
  13.  
    console.log("http://127.0.0.1:8080/6_ajax_处理IE浏览器GET请求缓存问题.html");
  14.  
    })
  15.  
     
学新通

6、ajax_处理 IE 浏览器 GET 请求缓存问题. html

IE缓存问题:每次请求的链接相同,IE发现链接与之前的相同,不与服务器连接,返回的还是之前的数据。

  1.  
    btn.onclick = function(){
  2.  
    // 1
  3.  
    const xhr = new XMLHttpRequest();
  4.  
    xhr.onreadystatechange = function(){
  5.  
    if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300)){
  6.  
    console.log(xhr.response);//返回的数据
  7.  
    }
  8.  
    }
  9.  
    // 2 指定发送请求的:method、url、参数
  10.  
    // 加个时间戳,使每次请求的链接不同
  11.  
    xhr.open('GET','http://127.0.0.1:8080/get_person?time=' Date.now())
  12.  
     
  13.  
    // responseType用于指定返回数据的格式
  14.  
    xhr.responseType='json'
  15.  
     
  16.  
    // 3 发送请求
  17.  
    xhr.send();
  18.  
    }
  19.  
     
学新通

2.7 ajax 请求的异常与超时处理

 xhr.onerror ( ) 处理请求异常

xhr.ontimeout ( ) 处理请求超时

server.js

  1.  
    const express = require('express');
  2.  
    const app = express();
  3.  
     
  4.  
    app.use(express.static(__dirname '/src'))
  5.  
    // 响应GET请求
  6.  
    app.get('/get_person',(request,response)=>{
  7.  
    console.log("有人请求get_person了");
  8.  
    const person ={name:'海峰',age:18,sex='女'}
  9.  
    response.send(JSON.stringify(person))
  10.  
    });
  11.  
     
  12.  
    // 延迟---响应GET请求
  13.  
    app.get('/get_person_delay',(request,response)=>{
  14.  
    console.log("有人请求get_person了");
  15.  
    const person ={name:'tom',age:18,sex='女'}
  16.  
    setTimeout(()=>{
  17.  
    //设置响应体
  18.  
    response.send(JSON.stringify(person));
  19.  
    },3000)
  20.  
     
  21.  
    });
  22.  
    app.listen(8000, () => {
  23.  
    console.log("服务已经启动,测试地址如下:");
  24.  
    console.log("http://127.0.0.1:8080/7_ajax_请求的异常与超时处理.html");
  25.  
    })
  26.  
     
学新通

7、ajax_请求的异常与超时处理. html

  1.  
    btn.onclick = function(){
  2.  
    // 1
  3.  
    const xhr = new XMLHttpRequest();
  4.  
    xhr.onreadystatechange = function(){
  5.  
    if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300)){
  6.  
    console.log(xhr.response);//返回的数据
  7.  
    }
  8.  
    }
  9.  
    // 2 指定发送请求的:method、url、参数
  10.  
    // xhr.open('GET','http://127.0.0.1:8080/get_person')
  11.  
    xhr.open('GET','http://127.0.0.1:8080/get_person_delay') //带延迟的
  12.  
     
  13.  
    // responseType用于指定返回数据的格式
  14.  
    xhr.responseType='json'
  15.  
     
  16.  
    // 出错的回调
  17.  
    xhr.onerror = function(){
  18.  
    alert('你的网络似乎出了一点问题');
  19.  
    }
  20.  
    // 超时时间
  21.  
    xhr.timeout = 2000;
  22.  
    // 超时的回调(如果超时了调用)
  23.  
    xhr.ontimeout = function(){
  24.  
    alert('网速不给力,超时了');
  25.  
    }
  26.  
    // 3 发送请求
  27.  
    xhr.send();
  28.  
    }
  29.  
     
学新通

2.8 ajax 取消请求 xhr.abort( )

8、ajax_取消请求. html

取消请求,有的是服务器接收了请求,取消之后没有返回;有的是服务器还没发过去就取消了。

  1.  
    let xhr; //定义在外面
  2.  
    const btn1 = document.getElementsByTagName('button')[0];
  3.  
    //取消的按钮
  4.  
    const btn2 = document.getElementsByTagName('button')[1];
  5.  
    btn1.onclick = function(){
  6.  
    xhr = new XMLHttpRequest();
  7.  
    xhr.onreadystatechange = function(){
  8.  
    if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300)){
  9.  
    console.log(xhr.response);//返回的数据
  10.  
    }
  11.  
    }
  12.  
    // 2 指定发送请求的:method、url、参数
  13.  
    xhr.open('GET','http://127.0.0.1:8080/get_person_delay') //带延迟的
  14.  
    // responseType用于指定返回数据的格式
  15.  
    xhr.responseType='json'
  16.  
    // 出错的回调
  17.  
    xhr.onerror = function(){
  18.  
    alert('你的网络似乎出了一点问题');
  19.  
    }
  20.  
    // 超时时间
  21.  
    xhr.timeout = 2000;
  22.  
    // 超时的回调
  23.  
    xhr.ontimeout = function(){
  24.  
    alert('网速不给力,超时了');
  25.  
    }
  26.  
    // 3 发送请求
  27.  
    xhr.send();
  28.  
    }
  29.  
     
  30.  
    btn2.onclick = function(){
  31.  
    // 取消请求,如果数据已经回来了就取消不了了,如果来得及就会取消
  32.  
    xhr.abort();
  33.  
    }
  34.  
     
学新通

2.9 避免多次重复请求

9、ajax_避免多次重复请求. html

  1.  
    let xhr; //定义在外面
  2.  
    let isLoading;// 是否正在发送AJAX请求
  3.  
    const btn1 = document.getElementsByTagName('button')[0];
  4.  
    btn1.onclick = function(){
  5.  
    // 设置标志位:如果已经发送请求,之前的就被干掉
  6.  
    if(isLoading) xhr.abort();
  7.  
     
  8.  
    // 1 实例xhr
  9.  
    xhr = new XMLHttpRequest();
  10.  
    xhr.onreadystatechange = function(){
  11.  
    if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300){
  12.  
    // 数据已经返回,将标志设为false
  13.  
    isLoading = false;
  14.  
    console.log(xhr.response);//返回的数据
  15.  
    }
  16.  
    }
  17.  
     
  18.  
    // 2 配置请求
  19.  
    xhr.open('GET','http://127.0.0.1:8080/get_person_delay') //带延迟的
  20.  
    xhr.responseType = 'json'
  21.  
     
  22.  
    // 3 发送请求
  23.  
    xhr.send();
  24.  
    isLoading = true;
  25.  
    }
  26.  
     
  27.  
    btn2.onclick = function(){
  28.  
    // 取消请求,如果数据已经回来了就取消不了了,如果来得及就会取消
  29.  
    xhr.abort();
  30.  
    }
  31.  
     
学新通

3、jQuery封装Ajax

server.js

  1.  
    const express = require('express');
  2.  
    const app = express();
  3.  
     
  4.  
    app.use(express.static(__dirname '/src'))
  5.  
     
  6.  
    // 响应GET请求
  7.  
    app.get('/test_jquery_get',(request,response)=>{
  8.  
    console.log("有人请求test_jquery_get了",request.query);
  9.  
    const car = {name:'马自达', price:'25万'}
  10.  
    response.send(JSON.stringify(car))
  11.  
    });
  12.  
     
  13.  
    // 响应POST请求
  14.  
    app.post('/test_jquery_post',(request,response)=>{
  15.  
    console.log("有人请求test_jquery_get了",request.body);
  16.  
    const car = {name:'马自达', price:'25万'}
  17.  
    response.send(JSON.stringify(car))
  18.  
    });
  19.  
     
  20.  
    app.listen(8000, () => {
  21.  
    console.log("服务已经启动,测试地址如下:");
  22.  
    console.log("http://127.0.0.1:8080/10_JQuery封装的ajax.html");
  23.  
    })
  24.  
     
学新通

10、JQuery 封装的 ajax.html

  1.  
    <!DOCTYPE html>
  2.  
    <html lang="en">
  3.  
    <head>
  4.  
    <meta charset="UTF-8">
  5.  
    <title>10_JQuery封装的ajax/title>
  6.  
    <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  7.  
    </head>
  8.  
    <body>
  9.  
    <h2 >jQuery封装的ajax</h2>
  10.  
    <button id="btn1">点我发送请求(JQuery-ajax-get)</button>
  11.  
    <button id="btn2">点我发送请求(JQuery-ajax-post)</button>
  12.  
    <button class="btn btn-info">通用型方法ajax</button>
  13.  
    <script type="text/javascript" >
  14.  
    const btn1=$('#btn1')
  15.  
    const btn2=$('#btn2')
  16.  
    const content=$('#content')
  17.  
     
  18.  
    // 1.使用jquery发送get请求(完整版)
  19.  
    btn1.click(()=>{
  20.  
    $.ajax({
  21.  
    url:'http://127.0.0.1/test_jquery_get',
  22.  
    method:'GET',//请求类型,默认get
  23.  
    dataType: 'JSON',//配置相应数据格式
  24.  
    data:{school:'atguigu'},//携带的数据
  25.  
    timeout: 2000,//超时时间
  26.  
    // 成功的回调
  27.  
    success:(result,responeText,xhr)=>{
  28.  
    // responeText:success,error
  29.  
    console.log(result,responeText,xhr);
  30.  
    content.append(`<div>汽车名:${result.name},价格${result.price}</div>`)
  31.  
    },
  32.  
    // 失败的回调
  33.  
    error:(xhr)=>{ console.log('请求出错了',xhr);}
  34.  
    })
  35.  
    })
  36.  
     
  37.  
    // 2.使用jquery发送get请求(精简版)
  38.  
    btn1.click(()=>{
  39.  
    $.get('http://127.0.0.1/test_jquery_get',{school:'atguigu'},(data)=>{
  40.  
    console.log(data);
  41.  
    },'json')
  42.  
    })
  43.  
     
  44.  
    // 3.使用jquery发送post请求(完整版)
  45.  
    btn1.click(()=>{
  46.  
    $.ajax({
  47.  
    url:'http://127.0.0.1/test_jquery_post',
  48.  
    method:'POST',//请求类型,默认get
  49.  
    dataType: 'JSON',//配置相应数据格式
  50.  
    data:{school:'atguigu'},//携带的数据
  51.  
    timeout: 2000,//超时时间
  52.  
    // 成功的回调
  53.  
    success:(result,responeText,xhr)=>{
  54.  
    //responeText:success,error
  55.  
    console.log(result,responeText,xhr);
  56.  
    content.append(`<div>汽车名:${result.name},价格${result.price}</div>`)
  57.  
    },
  58.  
    // 失败的回调
  59.  
    error:(xhr)=>{ console.log('请求出错了',xhr);}
  60.  
    })
  61.  
    })
  62.  
     
  63.  
    // 4.使用jquery发送post请求(精简版)
  64.  
    btn1.click(()=>{
  65.  
    $.post('http://127.0.0.1/test_jquery_post',{school:'atguigu'},(data)=>{
  66.  
    console.log(data);
  67.  
    },'json')
  68.  
    })
  69.  
     
  70.  
    </script>
  71.  
    </body>
  72.  
    </html>
  73.  
     
学新通

4、跨域

1. 同源:
如果两个页面(接口)的协议、域名、端口号都相同,我们认为他们具有相同的源学新通

2. 同源策略:
同源策略就是浏览器的一个安全限制它阻止了不同【域】之间进行的数据交互

3. 没有同源策略的危害:
如果没有同源策略的作用,任意站点之间可以操作资源,当你在访问一个合法网站的时候,又打开了一个恶意网站,包含了恶意脚本,恶意脚本便可以操作合法网站上的一切资源。

4. 非同源策略的限制:
1、不能获取不同源的 cookie,LocalStorage 和 indexDB
如果不同源可以获取用户的 cookie 信息等,被恶意的人加以操作,岂不是很可怕,所以这是为了防止恶意网站获取用户其他网站的 cookie 数据做出的限制。
2、不能让获取非同源的 DOM
举个栗子:如果没有这一条,恶意网站可以通过 iframe 打开银行页面,可以获取 dom 就相当于可以获取整个银行页面的信息。
3、不能发送非同源的 ajax 请求
(准确说应该是可以向非同源的服务器发起请求,但是返回的数据会被浏览器拦截)

4.1 JSONP 解决跨域(工作不用,面试常问)(手写)

1.JSONP 是什么

jsonp跨域其实也是JavaScript设计模式中的一种代理模式。在html页面中通过相应的标签从不同域名下加载静态资源文件是被浏览器允许的,所以我们可以通过这个“犯罪漏洞”来进行跨域。一般,我们可以动态的创建script标签,再去请求一个带参网址来实现跨域通信
JSONP 是一个非官方的跨域解决方法,纯粹凭借程序员的聪明才智开发出来,缺陷是只支持 get 请求。

绕开xhr,借助script标签发请求

有一种前端定义函数,后端调用函数的感觉。

总结:利用script标签的src属性不受同源策略限制的特点。

server.js

  1.  
    const express = require('express');
  2.  
    const app = express();
  3.  
     
  4.  
    app.use(express.static(__dirname '/src'))
  5.  
    // 响应GET请求
  6.  
    app.get('/test_jsonp',(request,response)=>{
  7.  
    //json.stringify()将JavaScript对象或值转换为JSON字符串
  8.  
    const person =[{name:'老刘',age:18},{name:'tom',age:20}]
  9.  
    //response.send(`demo(${JSON.stringify(person)})`)
  10.  
    const {callback} = request.query
  11.  
    response.send(`${callback}(${JSON.stringify(person)})`)
  12.  
    });
  13.  
    });
  14.  
    app.listen(8000, () => {
  15.  
    console.log("服务已经启动,测试地址如下:");
  16.  
    console.log("http://127.0.0.1:8080/13_JSONP解决跨域.html");
  17.  
    })
  18.  
     
学新通

13、JSONP 解决跨域. html

  1.  
    btn.onclick = function(){
  2.  
    // 1. 创建script节点
  3.  
    const scriptNode = document.createElement("script");
  4.  
    // 2. 给节点指定src属性(请求地址)
  5.  
    // 把函数名也传过去
  6.  
    scriptNode.src = 'http://localhost:8080/test_jsonp?callback=peiqi'
  7.  
    // 3. 将节点放入页面
  8.  
    document.body.appendChild(scriptNode)
  9.  
    const xhr = new XMLHttpRequest();
  10.  
    // window.demo=(a)=>{
  11.  
    // 4. 准备一个函数
  12.  
    // 动态的函数名
  13.  
    window.peqi=(a)=>{
  14.  
    console.log(a)
  15.  
    }
  16.  
    // 5. 移除已经使用过得script节点
  17.  
    document.body.removeChild(scriptNode)
  18.  
    }
  19.  
     
学新通

JSON 和 JSONP 的区别!
但到目前为止最被推崇或者说首选的方案还是用 JSON 来传数据,靠 JSONP 来跨域。
JSON 和 JSONP 虽然只有一个字母的差别,但其实他们根本不是一回事儿:JSON 是一种数据交换格式,而 JSONP 是一种非官方跨域数据交互协议。
jsonp 全名叫做 json with padding,很形象,就是把 json 对象用符合 js 语法的形式包裹起来以使其它网站可以请求得到,也就是将 json 数据封装成 js 文件;
json 是理想的数据交换格式,但没办法跨域直接获取,于是就将 json 包裹 (padding) 在一个合法的 js 语句中作为 js 文件传过去。这就是 json 和 jsonp 的区别,json 是想要的东西,jsonp 是达到这个目的而普遍采用的一种方法,当然最终获得和处理的还是 json。所以说 json 是目的,jsonp 只是手段。json 总会用到,而 jsonp 只有在跨域获取数据才会用到

JSONP 的缺点
1 它只支持 GET 请求而不支持 POST 等其它类型的 HTTP 请求
2 它只支持跨域 HTTP 请求这种情况,不能解决不同域的两个页面之间如何进行 JavaScript 调用的问题。
3 jsonp 在调用失败的时候不会返回各种 HTTP 状态码。
4 缺点是安全性。万一假如提供 jsonp 的服务存在页面注入漏洞,即它返回的 javascript 的内容被人控制的。那么结果是什么?所有调用这个 jsonp 的网站都会存在漏洞。于是无法把危险控制在一个域名下… 所以在使用 jsonp 的时候必须要保证使用的 jsonp 服务必须是安全可信的。

4.2 jQuery 封装 JSONP

  1.  
    const btn= $("#btn")
  2.  
    $("#btn").click(()=>{
  3.  
    $.getJSON("http://localhost:8080/test_jsonp?callback=?", {},(data)=>{
  4.  
    console.log(data);
  5.  
    });
  6.  
    });
  7.  
     

4.3 CORS 解决跨域(后端技术)

设置响应头 Access-Control-Allow-Origin

server.js

  1.  
    app.get('/test_get', (request, response) => {
  2.  
    console.log("有人请求test_get了,携带的query参数是:",request.query);
  3.  
    // 设置响应头
  4.  
    // Access-Control-Allow-Origin
  5.  
    response.setHeader("Access-Control-Allow-Origin", "*")//任何网站都可以拿数据
  6.  
    //response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500")
  7.  
    response.setHeader("Access-Control-Allow-Headers", '*');
  8.  
    response.setHeader("Access-Control-Allow-Method", '*');
  9.  
    response.send("Hello_test_get");
  10.  
    });
  11.  
    app.options('/test_put', (request, response) => {
  12.  
    response.setHeader("Access-Control-Allow-Origin", "*")
  13.  
    response.setHeader("Access-Control-Allow-Headers", '*');
  14.  
    response.setHeader("Access-Control-Allow-Method", '*');
  15.  
    response.send("Hello_test_get");
  16.  
    });
  17.  
    app.put('/test_put', (request, response) => {
  18.  
    response.setHeader("Access-Control-Allow-Origin", "*");
  19.  
    response.setHeader("Access-Control-Allow-Headers", '*');
  20.  
    response.setHeader("Access-Control-Allow-Method", '*');
  21.  
    response.send("Hello");
  22.  
    });
  23.  
     
学新通
  1.  
    btn.onclick = function(){
  2.  
    const xhr = new XMLHttpRequest();
  3.  
    xhr.onreadystatechange = function(){
  4.  
    if(xhr.readyState === 4 && (xhr.status >=200 && xhr.status<300)){
  5.  
    console.log(xhr.response);//返回的数据
  6.  
    }
  7.  
    }
  8.  
     
  9.  
    xhr.open('GET','http://localhost:8080/test_get')
  10.  
    //xhr.open('PUT','http://localhost:8080/test_get')
  11.  
    xhr.send()
  12.  
    }
  13.  
     

安装 cors
yarn add cors

server.js

  1.  
    // cors中间件
  2.  
    const cors = require('cors')
  3.  
    app.use(cors())
  4.  
    app.get('/test_get', (request, response) => {
  5.  
    console.log("有人请求test_get了,携带的query参数是:",request.query);
  6.  
    response.send("Hello_test_get");
  7.  
    });
  8.  
     

cors 解决跨域

  1. 前端无需任何操作,靠后端完成
  2. 不是两个响应头就可以实现,需要一组响应头
  3. put、delete 不是简单请求,属于复杂请求,在真正请求之前需要进行预请求(嗅探请求)

CORS 的优缺点:

CORS 的优点:可以发任意请求
CORS 的缺点:
上是复杂请求的时候得先做个预检,再发真实的请求。发了两次请求会有性能上的损耗

5 get 和 post

GET

  1. 含义:从指定的资源获取数据
  2. 什么时候使用 GET 请求较为合适?
    (1)单纯获取数据时
    (2)请求非敏感数据时
  3. 常见的 GET 请求:

1 浏览器地址栏输入网址时,(即浏览器请求页面时,且无法手动更改)
2 可以请求外部资源的 html 标签,例如:<img><a><link><script>且无法手动更改
3 发送 ajax 时若没有指定发送请求的方式,则使用功能 GET,或者明确指出了使用 GET 请求
4 form 表单提交时,若没有指明方式,则使用 get

POST

  1. 含义:想指定的资源提交要被处理的数据
  2. 什么时候使用 POST 请求较为合适?
    (1)传送相对敏感的数据时
    (2)请求的结果有持续性的副作用,例如:传递的数据要写入数据库时
    备注:使用 POST 不代表绝对的安全
  3. 常见的 POST 请求:

1 发送 ajax 时明确指出了使用 post 方式时
2 使用第三方发送请求库时明确指出用 post 方式
3 form 表单提交时明确指出 post 方式
学新通
get 就是浏览器地址栏会有一堆 key=value&key=value…

get请求和post请求的区别:
   ① post比get安全 (因为post参数在请求体body中,get参数在url上面)

   ② get传输速度比post快 根据传参决定的。(post通过请求体传参,后台通过数据流接收。速度稍微慢一些。而get通过url传参可以直接获取)

   ③ post传输文件大理论没有限制 ,get传输文件大概 2-8k 之间,更加常见的是1k以内

  ④ get请求刷新服务器或者回退没有影响,post请求回退时会重新提交数据请求。

  ⑤ get请求可以被缓存,post请求不会被缓存

  ⑥ get请求只能进行url编码(appliacation-x-www-form-urlencoded),post请求支持多种(multipart/form-data等)。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhekgbbk
系列文章
更多 icon
同类精品
更多 icon
继续加载