AJAX

作者: 你怀中的猫 | 来源:发表于2022-06-11 16:58 被阅读0次

一、完整的一个项目业务分为三个部分

1、前端部分:布局 + 交互 + 发送网路请求 (数据是不能动态储存的

2、后端部分: 响应前端网络请求 + 数据处理 + 数据库交互

3、数据库: 存储前端要显示的数据,实现数据的网络储存

二、项目业务流

前端发送请求
后端操作数据库
响应数据

  • 请求: request => req
  • 响应: response => res

三、ajax流程

1、创建xmlHttpRequest对象(xhr)

var xhr = new XMLHttpRequest();

2、xhr注册readystatechange事件处理函数

xhr.addEventListener('readystatechange',function(){
        if(xhr.readyState == 4){
           //console.log(xhr.status);  //网络请求状态码 2xx 4xx 5xx
            if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304 ){
               //获取后端回发的数据 xhr.responseText
               //console.log(xhr.responseText)
                var data = JSON.parse(xhr.responseText)
                alert("网络请求结束")
                console.log(data)
            }
        }
    
    })

3、请求配置 xhr.open(请求方式,url,true)

  • 1、bool值用来控制网络请求代码的执行顺序,true的异步,请求成功后回调
  • 2、如果写成false,网络请求之后的所有代码,都要等待网络请求结束后,才能执行,影响效率
xhr.open('post','127.0.0.1:3000/search',true);

4、设置请求头 xhr.setPequestHeader('content-Type'," ")

xhr.setRequestHeader('Content-Type',"application/x-www-form-urlencoded");

5、发送网络请求 xhr.send()

 xhr.send("content=大风吹&page=1"); 
  • 请求参数
    1、get请求:请求的键值对参数,拼接在请求url后面
    2、post请求:单纯键值对 xhr.send("拼接字符串")
//文件 + 键值对
var formData = new FormData()
formData.append('file',file.files[0])
xhr.send(formData)
  • 响应
    xhr.readyState : 表示当前请求的发送阶段
    0 ===》 xhr.open() 未调用
    1 ===》 xhr.send() 还没有被调用
    2 ===》 服务器尚未接通
    3 ===》 服务器接通,正在接收的服务器响应中
    4 ===》 响应服务器完毕,要接受的服务器数据,在第四个状态中
if(xhr.readyState == 4){
    if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
         xhr.responseText
     }
}

把ajax封装起来,需要传入参数,这里传入了一个options

function request(options){
    //接受传入的参数
    var url = options.url || '';
    //接收请求类型
    var type = options.type || 'get'; //设置默认值
    //接收请求参数data
    var data = options.data || {};
    //接收header
    var header = options.header || {'Content-Type':'application/x-www-form-urlencoded'};
    //接收参数
    var success = options.success;

    //发起网络请求
    var xhr = new XMLHttpRequest();
    //监听事件
    xhr.addEventListener('readystatechange',function(){
        if(xhr.readyState == 4){
            if(xhr.status >= 200 && xhr.status < 300 || xhr.status == 304){
                //获取响应
                var res = JSON.parse(xhr.responseText)
                //调用success
                if(typeof success == 'function'){
                    success(res)
                }
            }
        }
    })
    //对url进行处理
    //将data中的键值对进行遍历拼接成一组字符串  {key1:value1,key2:value2}  ==> key1:value1
    var strData = "";
    for(var key in data){
        var value = typeof data[key] == 'object' ? JSON.stringify(data[key]) : data[key];
        strData += `${key}=${value}&`;
    }
    strData = strData.replace(/\&$/,"");
    //请求地址 url?参数键值对字符串
    //判断如果type是get就给url后拼接 strData
    url = type == 'get' ? url + "?" + strData : url;

    //请求配置
    xhr.open(type,url,true)
    //配置请求头,遍历header对象,调用xhr.setRequestHeader(key,value)
    for(var key in header){
        //判断如果传入的data是一个formData,并且当前的key是Content-Type
        if(data instanceof FormData && key == 'Content-Type') continue ;
        xhr.setRequestHeader(key,header[key])
    }

    //发送请求(判断如果是post,需要在xhr.send(参数) 否则,直接 xhr.send())
    if(type == 'post'){
        //判断如果是formData 就直接使用,如果不是,就把参数换成键值对字符串
        data = data instanceof FormData ? data : strData;
        xhr.send(data);
    }else{
        //get
        xhr.send()
    }
   
}


//测试封装好的ajax
  request({
        url: "请求地址",
        type: 'get',
        success: function (res) {
            console.log(res)
        }
    })

JQ ajax基本书写形式

 $.ajax({
        url : "",
        type : 'get',
        //设置解析响应数据类型
        dataType : 'json',
        success : function(res){
            //请求成功
            console.log(res)
        },
        error : function(erro){
            //请求出错时 url路径错误
            console.log("请求出错",erro)
        }
    })

相关文章

  • AJAX

    主要内容: ajax 是什么、原生ajax 写法和jQuery ajax写法。 AJAX 是什么 ajax,即As...

  • JavaScript进阶知识点--AJAX及JSON

    AJAX 关于 AJAX 什么是 AJAX AJAX 的全称是 Asynchronous JavaScript a...

  • HTML5权威指南 | 第五部分 高级功能

    三十二、使用AJAX(上) Ajax起步: 使用Ajax事件: Ajax请求的错误处理: 中止Ajax请求: 三十...

  • ajax学习笔记

    Ajax学习笔记 Ajax简介 1. Ajax是什么? Ajax : Asynochronous javascri...

  • AJAX

    一、简介 AJAX菜鸟教程 什么是 AJAX ? AJAX = 异步 JavaScript 和 XML。 AJAX...

  • js之AJAX复习

    异步交互和同步交互 什么是Ajax? Ajax的工作原理。 Ajax包含的技术: Ajax的缺陷: Ajax的核心...

  • 复习jQuery - ajax

    jQuery ajax - ajax() 方法 $.ajax({ url:'oo.php', ...

  • jQuery中Ajax请求的使用和四个步骤示例

    ajax() 方法用于执行 AJAX(异步 HTTP)请求,所有的 jQuery AJAX 方法都使用 ajax(...

  • ajax

    1、什么是ajax? 2、ajax的原理 3、ajax的核心对象 4、ajax的优点: ajax的缺点: 被jqu...

  • ajax

    Ajax 1 - 请求纯文本 Ajax 2 - 请求JSON数据 Ajax 3 - 请求Github接口 Ajax...

网友评论

      本文标题:AJAX

      本文链接:https://www.haomeiwen.com/subject/lzcwmrtx.html