jQuery+AJAX请求的统一封装

记录一下使用jQuery+AJAX对http请求的统一封装

很久都没有使用jquery和ajax的组合了,这里记录一下jquery和ajax的组合简单封装 将来或许有机会重新启用这个组合

新建jquery.request.js;demo目录结构如下
myw


const baseURL = 'http://127.0.0.1:8116';

//  const baseURL = "";

const timeout = 3000;

// requet ajax
function request (url, method, data = {}, contentType, back){
    $.ajax({
        url: baseURL+url,
        type: method,
        data: data,
        cache: false,
        timeout: timeout,
        contentType: contentType,
        dataType: "json",
        success: function(res){
            console.log(res)
            return typeof back == "function" && back(res);
        },
        error: function(error) {
            console.log(error)
            return typeof back == "function" && back(null);
        }
    });   
};
function getAjaxRequst (url, data, callBack) {
    request(url, "GET", data, "application/x-www-form-urlencoded;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};
function postAjaxRequst (url, data, callBack) {
    request(url, "POST", data, "application/x-www-form-urlencoded;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};

index.html里jquery的引用必须放在request的前面

    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript" src="jquery.request.js"></script>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-siteapp">
    <meta name="keywords" content="">
    <meta name="description" content="">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript" src="jquery.request.js"></script>
    <title>jquery.request-demo</title>
    <style></style>
</head>

<body>

<div class="">

</div>
<script type="text/javascript">

    $(function() {
        requestGetLoginDemo();
        requestPostLoginDemo();
    });

    function requestGetLoginDemo() {
        var data = { username: "myyhtw", password: "123456"}
        getAjaxRequst('/auth/login', data, function(res) {
            console.log(res)
            if(res){
                console.log("需要的数据")
            } else {
                console.log("返回数据不存在或者请求数据失败")
            }
        })
    }

    function requestPostLoginDemo() {
        var data = { username: "myyhtw", password: "123456"}
        postAjaxRequst('/auth/login', data, function(res) {
            console.log(res)
            if(res){
                console.log("需要的数据")
            } else {
                console.log("返回数据不存在或者请求数据失败")
            }
        })
    }

    
</script>

</body>

</html>

后端使用SpringBoot写了get和post请求登录的2个接口示例
myw
myw
这里使用的是application/x-www-form-urlencoded;charset=UTF-8,一般我们使用的都是json数据,于是呢可以改变下jquery.request.js

application/json;charset=UTF-8

// requet ajax json token
function httpJsonRequest (url, method, data = {}, token, contentType, back){
    $.ajax({
        url: baseURL+url,
        type: method,
        data: JSON.stringify(data),
        cache: false,
        timeout: timeout,
        headers: {'token': token},
        contentType: contentType,
        dataType: "json",
        success: function(res){
            console.log(res)
            return typeof back == "function" && back(res);
        },
        error: function(error) {
            console.log(error)
            return typeof back == "function" && back(null);
        }
    });   
};
function getAjaxJsonHttpRequst (url, data, token, callBack) {
    httpJsonRequest(url, "GET", data, token, "application/json;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};
function postAjaxJsonHttpRequst (url, data, token, callBack) {
    httpJsonRequest(url, "POST", data, token, "application/json;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};

index.html

$(function() {
    requestJsonGetLoginDemo();
    requestJsonPostLoginDemo();
});

function requestJsonGetLoginDemo() {
    var username = "myyhtw"; 
    var password = "123456";
    getAjaxJsonHttpRequst('/auth/login/'+username+"/"+password, null, null, function(res) {
        console.log(res)
        if(res){
            console.log("需要的数据")
        } else {
            console.log("返回数据不存在或者请求数据失败")
        }
    })
}

function requestJsonPostLoginDemo() {
    var data = { username: "myyhtw", password: "123456"}
    postAjaxJsonHttpRequst('/auth/login', data, null, function(res) {
        console.log(res)
        if(res){
            console.log("需要的数据")
        } else {
            console.log("返回数据不存在或者请求数据失败")
        }
    })
}

后端使用SpringBoot写了get和post请求json格式登录的2个接口示例

myw
myw

完整jquery.request.js



const baseURL = 'http://127.0.0.1:8116';

//  const baseURL = "";

const timeout = 3000;

// requet ajax
function request (url, method, data = {}, contentType, back){
    $.ajax({
        url: baseURL+url,
        type: method,
        data: data,
        cache: false,
        timeout: timeout,
        contentType: contentType,
        dataType: "json",
        success: function(res){
            console.log(res)
            return typeof back == "function" && back(res);
        },
        error: function(error) {
            console.log(error)
            return typeof back == "function" && back(null);
        }
    });   
};
function getAjaxRequst (url, data, callBack) {
    request(url, "GET", data, "application/x-www-form-urlencoded;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};
function postAjaxRequst (url, data, callBack) {
    request(url, "POST", data, "application/x-www-form-urlencoded;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};


// requet ajax json token
function httpJsonRequest (url, method, data = {}, token, contentType, back){
    $.ajax({
        url: baseURL+url,
        type: method,
        data: JSON.stringify(data),
        cache: false,
        timeout: timeout,
        headers: {'token': token},
        contentType: contentType,
        dataType: "json",
        success: function(res){
            console.log(res)
            return typeof back == "function" && back(res);
        },
        error: function(error) {
            console.log(error)
            return typeof back == "function" && back(null);
        }
    });   
};
function getAjaxJsonHttpRequst (url, data, token, callBack) {
    httpJsonRequest(url, "GET", data, token, "application/json;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};
function postAjaxJsonHttpRequst (url, data, token, callBack) {
    httpJsonRequest(url, "POST", data, token, "application/json;charset=UTF-8", function(res) {
        return typeof callBack == "function" && callBack(res)
    })
};




index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-siteapp">
    <meta name="keywords" content="">
    <meta name="description" content="">
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript" src="jquery.request.js"></script>
    <title>jquery.request-demo</title>
    <style></style>
</head>

<body>

<div class="">

</div>
<script type="text/javascript">

    $(function() {
        // requestGetLoginDemo();
        // requestPostLoginDemo();
        requestJsonGetLoginDemo();
        requestJsonPostLoginDemo();
    });

    function requestJsonGetLoginDemo() {
        var username = "myyhtw"; 
        var password = "123456";
        getAjaxJsonHttpRequst('/auth/login/'+username+"/"+password, null, null, function(res) {
            console.log(res)
            if(res){
                console.log("需要的数据")
            } else {
                console.log("返回数据不存在或者请求数据失败")
            }
        })
    }

    function requestJsonPostLoginDemo() {
        var data = { username: "myyhtw", password: "123456"}
        postAjaxJsonHttpRequst('/auth/login', data, null, function(res) {
            console.log(res)
            if(res){
                console.log("需要的数据")
            } else {
                console.log("返回数据不存在或者请求数据失败")
            }
        })
    }


    function requestGetLoginDemo() {
        var data = { username: "myyhtw", password: "123456"}
        getAjaxRequst('/auth/login', data, function(res) {
            console.log(res)
            if(res){
                console.log("需要的数据")
            } else {
                console.log("返回数据不存在或者请求数据失败")
            }
        })
    }

    function requestPostLoginDemo() {
        var data = { username: "myyhtw", password: "123456"}
        postAjaxRequst('/auth/login', data, function(res) {
            console.log(res)
            if(res){
                console.log("需要的数据")
            } else {
                console.log("返回数据不存在或者请求数据失败")
            }
        })
    }

    
</script>

</body>

</html>

http://www.niftyadmin.cn/n/5098649.html

相关文章

加拿大AI医疗技术公司【FluidAI】完成1500万美元融资

来源&#xff1a;猛兽财经 作者&#xff1a;猛兽财经 猛兽财经获悉&#xff0c;总部位于加拿大基奇纳的AI医疗技术公司【FluidAI】今日宣布已完成1500万美元融资。 本轮融资由SOSV和Graphene Ventures领投&#xff0c;参与方包括Boutique Venture Partners、Threshold Impact、…

javaScript的简单应用

javaScript是什么&#xff1f; 是一种运行在客户端&#xff08;浏览器&#xff09;的编程语言&#xff0c;实现人机交互的效果 2.作用 -网页特效&#xff08;监听一些行为让网页做出对应的反馈&#xff09; 表单验证&#xff08;针对表单的数据合法的进行判断-&#xff09; …

瑞吉外卖项目详细分析笔记及所有功能补充代码

目录 项目刨析简介技术栈项目介绍项目源码 一.架构搭建1.初始化项目结构2.数据库表结构设计3.项目基本配置信息添加公共字段的自动填充全局异常处理类返回结果封装的实体类 二.管理端业务开发1.员工管理相关业务1.1员工登录1.2员工退出1.3过滤器拦截1.4员工信息修改1.5员工信息…

CSS详细解析二

05-显示模式 显示模式&#xff1a;标签&#xff08;元素&#xff09;的显示方式。 作用&#xff1a;布局网页的时候&#xff0c;根据标签的显示模式选择合适的标签摆放内容。 块级元素 特点&#xff1a; 独占一行 宽度默认是父级的100% 添加宽高属性生效 行内元素 特…

Nginx正向代理,反向代理,负载均衡

Nginx正向代理&#xff0c;反向代理&#xff0c;负载均衡 Nginx当中有两种代理方式&#xff1a; 七层代理&#xff08;http协议&#xff09; 四层代理&#xff08;tcp/udp流量转发&#xff09; 七层代理&#xff1a;七层代理&#xff0c;代理的是http的请求和响应 客户端请求…

基于SSM的视频播放系统的设计与实现

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;Vue 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#xff1a;是 目录…

HTML 表格及练习

表格 概述 表格是一种二维结构&#xff0c;横行纵列。 由单元格组成。 表格是一种非常“强” 的结构&#xff1a; 每一行有相同的列数&#xff08;单元格&#xff09;&#xff0c;每一列有相同的行数&#xff08;单元格&#xff09; 同一列的单元格&#xff0c;宽度&#…

【视觉算法系列1】使用 KerasCV YOLOv8 进行红绿灯检测(下)

提示&#xff1a;免费获取本文涉及的完整代码与数据集&#xff0c;请联系助理老师peaeci122 使用最新“KerasCV YOLOv8”模型进行红绿灯检测的综合指南 YOLO目标检测模型已经进入了无数的应用领域&#xff0c;从监控系统到自动驾驶汽车。那么&#xff0c;如果在KerasCV框架下…