AJAX发送get、post请求及部分优化的简单理解

  • XMLHttpRequest对象是AJAX技术的核心
  • 简单来讲,AJAX发送并接受响应一共为四步
let xhr = new XMLHttpRequest(); //建立XMLHttpRequest对象实例

xhr.open();                     //与服务端创建链接

xhr.send();                     //发送请求

xhr.onreadystatechange          //处理响应
复制代码

注:IE中有三种不一样的XHR对象,咱们这里只谈最经常使用的,适用于IE7及以上的前端

原生AJAX发送get请求

  • get请求很简单,由于get请求没有请求体,数据都是放置于URL后的,因此咱们只须要使用拼串方法便可 注:xhr.open方法中有三个参数(请求方法,拼串后的URL,是否异步传输),第三个参数由于默认是true(异步)因此能够省略

前端页面代码ajax

let xhr = new XMLHttpRequest();

xhr.open('get','URL?value=string');//将拼串的URL放置此

xhr.send();

xhr.onreadystatechange = function(){
    if(xhr.readyState === 4 && xhr.status === 200){
        //接受响应的操做
    }
}
复制代码

接收响应操做

readyState表明XHR对象所处于的状态,他有5个值express

  • readyState = 0,还没有调用open方法
  • readyState = 1,调用了open方法,但数据尚未发送
  • readyState = 2,数据已经发送,但没有接收到响应
  • readyState = 3,接收到部分响应
  • readyState = 4,接收到所有响应,能够查看

XHR对象接收到所有响应后,数据会填满对象,此时须要调用onreadystatechange方法来监控XHR所处于的状态,由于每当readyState数值发生变化,都会调用一次onreadystatechange方法后端

简单优化

咱们通常在readyState = 4状态时操做响应数据,而且咱们会监控服务端返回的状态码浏览器

当以2开头时,服务器返回的响应即为正确,除此以外,304的意思为页面正确且会重定向到浏览器已有的缓存文件,因此咱们能够将接收操做处改成缓存

xhr.onreadystatechange = function(){
    if(xhr.readyState === 4 && ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)){
        //接受响应的操做
    }
}
复制代码

Node服务器代码bash

app.get('/',(req,res)=>{
    console.log(req.query);//get请求使用query参数接收
    res.send('ok')
});
复制代码

原生AJAX发送post请求

  • post与get方法不一样的点在于,post方法发送的数据在请求体中,而且须要设置请求头

前端页面代码服务器

let xhr = new XMLHttpRequest();

xhr.open('post','http://localhost:8088');//不须要拼串了

xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');//设置请求头

xhr.send('key=value');                  //发送数据(请求体)

xhr.onreadystatechange = function(){
    if(xhr.readyState === 4 && xhr.staus === 200){
        //接受响应的操做
    }
}
复制代码

与前端页面同样,后端post也与get请求略微不一样app

  • 首先,后端接受post请求的参数并非query而是body
  • 其次,Node并不能直接解析post请求,而是须要经过中间件

Node服务器代码异步

app.use(express.urlencoded({extended:true}))//我使用的是express内置的中间件

app.post('/',(req,res)=>{
    let {key} = req.body;                   //咱们能够直接使用解构赋值来获取body中相应的值
    console.log({key});
    res.send('ok');
})
复制代码

jQuery封装AJAX

  • jQuery自己对AJAX进行了封装,有两种写法,效果都同样 前端页面代码
标准写法:
$.ajax('请求的地址',{
    method:'',				//请求的方法
    data:{},				//请求的数据
    dataType:'',       //响应的数据类型
    success:(result)=>{},	//成功回调
    error:(err)=>{}			//失败回调
})

简写:
$.get/post('请求地址',data,(data(响应的数据),success,xhr)=>{},dataType)
复制代码

Promise封装AJAX发送get请求

  • 咱们都知道Promise是前端进行异步操做的一种方法,并且经过上面的知识,咱们应该差很少了解了AJAX的基本用法,咱们如今就能够根据jQuery的格式简单封装一下

前端页面代码

let sendAjax = function (method,url,data){
    return new Promise(()=>{
        let xhr = new XMLHttpRequest();
        
        //判断是’get‘请求仍是’post‘请求
        if(method.toLowerCase() === 'get'){ 
            url += ('?' + data);      //get请求须要进行拼串操做

            xhr.open(method,url);

            xhr.send();
        }else   if(method.toLowerCase() === 'post'){
            xhr.open(method,url);

            xhr.setRequestHeader('content-Type','application/x-www-form-urlencoded')

            xhr.send(data);

        }

        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)){
                //接受响应的操做
                resolve();  //返回成功
            }else{
                reject();   //返回失败
            }
        }
    })
}

function clickB(){
    sendAjax('post','http://localhost:8088','a=1')
}
复制代码

优化

  • 咱们在上面已经进行了简单的封装,但咱们输入数据通常都是以对象的方式进行存储,那么,咱们就须要将对象转化为URL的格式
  • 这里咱们主要使用reduce累计的特性,来达到获取对象中全部属性值的目的
let keys = Object.keys(data);               //获取全部的key值
if(data instanceof Object){                 //判断是否为对象,若是不是能够将其转化为对象
   data =  keys.reduce((pre,now)=>{         //使用reduce方法累计附加对象中的key和value
       return pre += `${now}=${data[now]}&`;//使用模板字符串来简化写法
   },'')
}
复制代码

最终版

let value = {
        name:'sys',
        age:18
    }
    let sendAjax = function (method,url,data){
        return new Promise(()=>{
            let xhr = new XMLHttpRequest();

            let keys = Object.keys(data);
            if(data instanceof Object){
                data =  keys.reduce((pre,now)=>{
                    return pre += `${now}=${data[now]}&`;
                },'')
            }

            if(method.toLowerCase() === 'get'){
                url += ('?'+ data);

                xhr.open(method,url);

                xhr.send();
            }else
            if(method.toLowerCase() === 'post'){
                xhr.open(method,url);

                xhr.setRequestHeader('content-Type','application/x-www-form-urlencoded')

                xhr.send(data);

            }

            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4 && xhr.staus === 200){
                    //接受响应的操做
                }
            }
        })
    }
    function clickB(){
        sendAjax('get','http://localhost:8088',value)
    }
复制代码

借鉴:《JavaScript高级程序设计》 + 网上查找 + 本身的理解

若有错误,但愿提出

但愿你们都能早日拿到心仪的offer,加油,共勉

相关文章
相关标签/搜索