封装ajax和cookie操作 进行简单交互

博客围绕信息技术展开,主要内容包括封装ajax、用promise封装ajax、搭建服务器、封装cookie操作以及设置超时。这些操作在前端和后端开发中较为常见,有助于提升开发效率和优化用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

封装ajax

function ajax(options){
    if(options.url===undefined || typeof(options.url)!=="String") return;
    if(!(options.method===undefined || /^(get|post)$/i.test(options.method))) return;
    if(!(options.data===undefined || /^(.+=.+&?)$/i.test(options.data))) return;
    if(!(options.async === undefined || typeof(options.async) === 'boolean')) return;
    if(!(options.success === undefined || typeof(options.success) === 'function')) return;
    const _default = {
        url: options.url,
        method: options.method.toUpperCase()  || "GET",
        data: options.data || "",
        async: options.async || true,
        success: options.success || function(){}
    }
    if(_default.method === "GET" && _default.data === ""){
        _default.url=_default.url+"?"+_default.data;
    }
    if(_default.method === "POST" && _default.data !== ""){
        _default.url=_default.url;
    }
    const xhr =new XMLHttpRequest();
    xhr.open(_default.method,_default.url,_default.async);
    xhr.addEventListener("readystatechange",readyHandler);
    function readyHandler(){
        _default.success(xhr.responseText);
        xhr.removeEventListener("readystatechange",readyHandler);
    }
    if(_default.method==="POST"){
        xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
        xhr.send(_default.data);
    }else{
        xhr.send()
    }

promise 封装ajax

        function ajax(data,type="GET"){
            var url="http://127.0.0.1:4010";
            var str="";
            for(var prop in data){
                str+=prop+"="+data[prop]+"&";
                // str+=`${prop}=${data[prop]}&`;   ES6
            }
            str=str.slice(0,-1);
            return new Promise(function(resolve,reject){
                if(type.toLowerCase()==="get"){
                    url+="?"+str;
                }
                var xhr=new XMLHttpRequest();
                xhr.open(type,url);
                xhr.send(type.toLowerCase()==="get" ? null : str);
                xhr.onload=function(){
                    resolve(xhr.response);
                }
                xhr.onerror=function(){
                    reject();
                }
            })
        }

        ajax({user:"lys",age:25},"POSt").then(function(res){
            console.log(res);
        })

服务器搭建

var http=require("http");
var querystring=require("querystring");
var server=http.createServer(function(req,res){
    var data="";
    res.writeHead(200,{
        "content-type":"text/html;charset=utf-8",
        "Access-Control-Allow-Origin":"*"
    });
    
    req.on("data",function(_data){
        data+=_data;
    });
    req.on("end",function(){
        if(req.method.toUpperCase()==="GET"){
            if(req.url.includes("favicon.ico")) return res.end();;
            data=req.url.includes("?") ? req.url.split("?")[1] : "";
        }
        try{
            data=JSON.parse(data);
        }catch(e){
            data=data ? querystring.parse(data) : {};
        }
        console.log(data,req.method);
        res.write(JSON.stringify(data));
        res.end();
    });
});
server.listen(4010,"127.0.0.1",function(){
    console.log("服务器已开启");
});

//使用node开启服务

封装cookie操作

function setCookie(key,value,expires){
  if (expires === undefined){
    document.cookie=key+'='+value;
    return}
  const time=new Date();
  time.setTime(time.getTime()-1000*60*60*8+1000*expires);
  document.cookie=key+'=' +value+';expires='+time;
}

function getCookie(key){
  const obj={}const tmp=document.cookie.split('; ')for (let i=0;i<tmp.length;i++){
    const t=tmp[i].split('=');
    obj[t[0]]=t[1]}if(key === undefined){
    return obj;
  }else{
    return obj[key]}
}

function delCookie(key){
  setCookie(key, '', -1)}

超时设置

 xhr.timeout = 2000;
 xhr.ontimeout = function() {
           alert("网络延迟,请稍后再试");
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MaxLoongLvs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值