AJAX学习笔记6 JQuery对AJAX进行封装

AJAX学习笔记5同步与异步理解_biubiubiu0706的博客-CSDN博客

AJAX请求相关的代码都是类似的,有很多重复的代码,这些重复的代码能不能不写,能不能封装一个工具类。要发送ajax请求的话,就直接调用这个工具类中的相关函数即可。

用JS发送AJAX请求回顾

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AJAX发送GET POST</title>
</head>
<body>
<script type="text/javascript">
    window.onload=function (){
        document.getElementById("btn1").onclick=function(){
            var xhr=new XMLHttpRequest();
            xhr.onreadystatechange=function(){
                if(this.readyState==4){
                    if(this.status==200){
                        console.log("发送成功")
                    }
                }else{
                    console.log("得到错误响应")
                }
            }
            xhr.open("get","/xxxx",true)
            xhr.send()
        }
        document.getElementById("btn2").onclick=function(){
            var xhr=new XMLHttpRequest();
            xhr.onreadystatechange=function(){
                if(this.readyState==4){
                    if(this.status==200){
                        console.log("发送成功")
                    }
                }else{
                    console.log("得到错误响应")
                }
            }
            var username=document.getElementById("username").value
            xhr.open("get","/xxxx?username"+username,true)
            xhr.send()
        }

        document.getElementById("btn3").onclick=function(){
            var xhr=new XMLHttpRequest();
            xhr.onreadystatechange=function(){
                if(this.readyState==4){
                    if(this.status==200){
                        console.log("发送成功")
                    }
                }else{
                    console.log("得到错误响应")
                }
            }
            xhr.open("post","/xxxx"+username,true)
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")

            var username2=document.getElementById("username2").value;
            xhr.send("username="+username2)
        }
    }
</script>

<button id="btn1">发送GET无参</button>

<button id="btn2">发送GRT有参</button>
<input type="text" id="username">

<button id="btn3">发送POST有参</button>
<input type="text" id="username2">
</body>
</html>

响应结果一般是个字符串 也有可能是responseXML

一般现在都用JSON字符串

那么需要转成JS对象

复制代码
JSON.parse(this.responseText)

使用JQuery工具类中的AJAX方法来发送请求

引入

$.ajax() 是 jQuery 提供的一个通用 AJAX 请求方法.

$.get()$.ajax() 方法的一个简化版本,专门用于发送 GET 请求。

$.post()$.ajax() 方法的一个简化版本,专门用于发送 POST 请求。

示例

复制代码
$.get(url, [data], [callback])

$.get('http://www.liulongbin.top:3006/api/getbooks', function(res) {
    console.log(res) // 这里的 res 是服务器返回的数据
})

$.post(
   'http://www.liulongbin.top:3006/api/addbook', // 请求的URL地址
   { bookname: '水浒传', author: '施耐庵', publisher: '上海图书出版社' }, // 提交的数据
   function(res) { // 回调函数
      console.log(res)
   }
)

.ajax()比较通过,可以发送put,delete请求 但是.get()和.post()是简化版,暂没有.put和$.delete的写法

下面来完整的写几个示例

$.get()的写法

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JQuery发送AJAX请求</title>
</head>
<body>
<!--引入JQuery-->
<script type="text/javascript" src="ajax/js/jquery-3.4.1.js"></script>
<script type="text/javascript">
    $(function (){//页面加载完毕执行的函数    JQuery的写法  JS的写法--->window.onload=function(){}
        $("#btn1").click(function(){//JQuery写法    JS的写法  document.getElementById("btn1").onclick=function(){
            var username=$("#username").val()//var username=document.getElementById("username").value;
                //发送ajax请求
            $.get("/ajax/JQGET","username="+username,function(data){
                console.log(data)
                $("#div1").html(data)//原来的写法document.getElementById("div1").innerText=data
            })
        })
    })


</script>
<button id="btn1">发送AJAX GET请求</button><br>
用户名:<input type="text" id="username"><br>
<div id="div1"></div>
</body>
</html>

如果不想带参数,就把参数去掉

$.ajax()写法

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AJAX发送GET请求</title>
</head>
<body>
<script type="text/javascript" src="ajax/js/jquery-3.4.1.js"></script>
<script type="text/javascript">
    $(function(){
        //点击事件
        $("#btn1").click(function(){
            //发送AJAX请求
            $.ajax({
                type:"get",
                url:"/ajax/JQGET",
                data:"username="+$("#username").val(),
                async:true,
                success:function(data){
                    console.log(data)
                    $("#div1").html(data)
                }
            })
        })
    })
</script>
<button id="btn1">发送AJAX GET请求</button><br>
用户名:<input type="text" id="username"><br>
<div id="div1"></div>
</body>
</html>

后端随便返回点啥

发送$.post 无参请求

发送$.ajax()post有参数请求

注意

$.get()或者$.post() 方法默认发送的请求是异步的。

如果希望发送的请求可以改变同步或者异步 建议使用$.ajax()这种方式

用$.ajax()方式发送请求的示例

相关推荐
_落纸1 天前
三大基础无源电子元件——电阻(R)、电感(L)、电容(C)
笔记
Alice-YUE1 天前
【CSS学习笔记3】css特性
前端·css·笔记·html
2303_Alpha1 天前
SpringBoot
笔记·学习
萘柰奈1 天前
Unity学习----【进阶】TextMeshPro学习(三)--进阶知识点(TMP基础设置,材质球相关,两个辅助工具类)
学习·unity
沐矢羽1 天前
Tomcat PUT方法任意写文件漏洞学习
学习·tomcat
好奇龙猫1 天前
日语学习-日语知识点小记-进阶-JLPT-N1阶段蓝宝书,共120语法(10):91-100语法+考え方13
学习
向阳花开_miemie1 天前
Android音频学习(十八)——混音流程
学习·音视频
工大一只猿1 天前
51单片机学习
嵌入式硬件·学习·51单片机
c0d1ng1 天前
量子计算学习(第十四周周报)
学习·量子计算
Hello_Embed1 天前
STM32HAL 快速入门(二十):UART 中断改进 —— 环形缓冲区解决数据丢失
笔记·stm32·单片机·学习·嵌入式软件