Ajax学习

时间:2022-05-27 20:07:23   收藏:0   阅读:11

AJAX学习

一、HTTP

HTTP(hypertext transport protocol)协议『超文本传输协议』,协议详细规定了浏览器和万维网服务器之间互相通信的规则。 约定, 规则

1. 请求报文

重点是格式与参数

行      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

2. 响应报文

行      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>
404

403

401

500

200

二、express的使用

在nodejs已安装的情况下,进入创建的空文件夹中,

具体官网指南:https://www.expressjs.com.cn/starter/installing.html

npm init //通过 npm init 命令为你的应用创建一个 package.json 文件
npm install express //安装依赖
?

三、原生AJAX

1. get

//1. 创建对象
const xhr = new XMLHttpRequest();
//设置响应体数据的类型
xhr.responseType = ‘json‘;
//2. 初始化 设置请求方法和 url
xhr.open(‘GET‘, ‘http://127.0.0.1:8000/server?a=100&b=200&c=300‘);
//3. 发送
xhr.send();
//4. 事件绑定 处理服务端返回的结果
// on  when 当....时候
// readystate 是 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){
      //处理结果  行 头 空行 体
      //响应 
      // console.log(xhr.status);//状态码
      // console.log(xhr.statusText);//状态字符串
      // console.log(xhr.getAllResponseHeaders());//所有响应头
      // console.log(xhr.response);//响应体
      //设置 result 的文本
      result.innerHTML = xhr.response;
    }else{
?
    }
  }
}

 

2. post

//1. 创建对象
const xhr = new XMLHttpRequest();
//2. 初始化 设置类型与 URL
xhr.open(‘POST‘, ‘http://127.0.0.1:8000/server‘);
//设置响应体数据的类型
xhr.responseType = ‘json‘;
//设置请求头
xhr.setRequestHeader(‘Content-Type‘,‘application/x-www-form-urlencoded‘);
// xhr.setRequestHeader(‘name‘,‘atguigu‘);
//3. 发送
?
xhr.send(‘a=100&b=200&c=300‘);
// xhr.send(‘a:100&b:200&c:300‘);
// xhr.send(‘1233211234567‘);
?
//4. 事件绑定
xhr.onreadystatechange = function(){
  //判断
  if(xhr.readyState === 4){
    if(xhr.status >= 200 && xhr.status < 300){
      //处理服务端返回的结果
      result.innerHTML = xhr.response;
    }
  }
}

3. 请求中的其他问题

  1. 缓存问题

    通过在请求后面加上当前时间例如http://127.0.0.1:8000/server?t=Date.now() 通过获取当前时间不掉用缓存里的数据。

  2. 超时与网络异常;取消请求

    //超时设置 ms单位
    xhr.timeout = 2000;
    //超时回调
    xhr.ontimeout = function(){
      alert("网络异常, 请稍后重试!!");
    }
    //网络异常回调
    xhr.onerror = function(){
      alert("你的网络似乎出了一些问题!");
    }
    // 取消请求
    xhr.abort();
  3. 重复发送问题

    let isSending = false; // 是否正在发送AJAX请求
    btns[0].onclick = function(){
      //判断标识变量
      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;
        }
      }
    }
    ?
    // abort
    btns[1].onclick = function(){
      x.abort();
    }

四JQuery

1. 通用方法

$.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
  }
});

2. get

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

3. post

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

五axios

1. 通用方法

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);
})

2. get

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

3. post

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

六、fetch

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

七、跨域

1. 同源策略

const x = new XMLHttpRequest();
//这里因为是满足同源策略的, 所以 url 可以简写
x.open("GET",‘/data‘);
//发送
x.send();
//
x.onreadystatechange = function(){
  if(x.readyState === 4){
    if(x.status >= 200 && x.status < 300){
      console.log(x.response);
    }
  }
}

2. jsonp实现跨域

实际案例进行实现

let username = this.value;
//向服务器端发送请求 检测用户名是否存在
//1. 创建 script 标签
const script = document.createElement(‘script‘);
//2. 设置标签的 src 属性
script.src = ‘http://127.0.0.1:8000/check-username‘;
//3. 将 script 插入到文档中
document.body.appendChild(script);
// 可以实现到跨域请求实现

 

$.getJSON(‘http://127.0.0.1:8000/jquery-jsonp-server?callback=?‘, function(data){
    $(‘#result‘).html(`名称: ${data.name}<br>校区: ${data.city}`)
  });  

 

3. CORS

const btn = document.querySelector(‘button‘);
btn.onclick = function(){
  //1. 创建对象
  const x = new XMLHttpRequest();
  //2. 初始化设置
  x.open("GET", "http://127.0.0.1:8000/cors-server");
  //3. 发送
  x.send();
  //4. 绑定事件
  x.onreadystatechange = function(){
    if(x.readyState === 4){
      if(x.status >= 200 && x.status < 300){
        //输出响应体
        console.log(x.response);
      }
    }
  }
}

 

 

原文:https://www.cnblogs.com/MrChen-/p/15340554.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!