ajax&axios入门

本文详细介绍了AJAX的基本概念、作用,包括同步与异步的区别,并通过实例展示了原生JavaScript实现AJAX的步骤。接着,文章讲解了Axios库的使用,包括其简化AJAX请求的方式,以及GET和POST请求的别名方法。最后,提到了jQuery中发送Ajax请求的方法。
摘要由CSDN通过智能技术生成

3.Ajax

3.1 概述

AJAX (Asynchronous JavaScript And XML):异步的 JavaScript 和 XML。

我们先来说概念中的 JavaScriptXMLJavaScript 表明该技术和前端相关;XML 是指以此进行数据交换。而这两个我们之前都学习过。

3.1.1 作用

AJAX 作用有以下两方面:

  1. 与服务器进行数据交换:通过AJAX可以给服务器发送请求,服务器将数据直接响应回给浏览器。如下图

  2. 异步交互:可以在不重新加载整个页面的情况下,与服务器交换数据并更新部分网页的技术,如:搜索联想、用户名是否可用校验,等等…

3.1.2 同步和异步

知道了局部刷新后,接下来我们再聊聊同步和异步:

  • 同步发送请求过程如下

在这里插入图片描述

​ 浏览器页面在发送请求给服务器,在服务器处理请求的过程中,浏览器页面不能做其他的操作。只能等到服务器响应结束后才能,浏览器页面才能继续做其他的操作。

  • 异步发送请求过程如下
    在这里插入图片描述

    浏览器页面发送请求给服务器,在服务器处理请求的过程中,浏览器页面还可以做其他的操作。

3.2 快速入门

3.2.1 服务端实现

在项目创建名为 AjaxServlet 的servlet

@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 响应数据
        response.getWriter().write("hello ajax~");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
3.2.2 客户端实现

webapp 下创建名为 html的页面,在该页面书写ajax` 代码

  • 创建核心对象,不同的浏览器创建的对象是不同的

     var xhttp;
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
  • 发送请求

    //建立连接
    xhttp.open("GET", "http://localhost:8080/ajax-demo/ajaxServlet");
    //发送请求
    xhttp.send();
    
  • 获取响应

    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            // 通过 this.responseText 可以获取到服务端响应的数据
            alert(this.responseText);
        }
    };
    

3.3 原生Ajax使用的完整代码

xhr发起GET请求步骤:

// 1. 创建一个ajax的核心 XHR 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数,使用open 创建请求
xhr.open('GET', 'http://www.qwercfg.vip/api/test')
// 3. 调用 send 函数
xhr.send()
// 4. 为xhr.onreadystatechange  设置监听事件
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        // 获取服务器响应的数据
        console.log(xhr.responseText)
    }
}

xhr发起POST请求步骤:

// 1. 创建一个ajax的核心 xhr 对象
var xhr = new XMLHttpRequest()
// 2. 调用 open 函数,使用open 创建请求
xhr.open('POST', 'http://www.qwercfg.vip/api/test')
// 3. 设置请求头(如果是post请求  必须要写请求头)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// 4. 调用 send 函数(在这里添加参数)
xhr.send('name=哈哈哈&age=18')
// 5. 为xhr.onreadystatechange  设置监听事件
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText)
    }
}

4.axios

Axios 对原生的AJAX进行封装,简化书写。

Axios官网是:https://www.axios-http.cn

4.1 基本使用

axios 使用是比较简单的,分为以下两步:

  • 引入 axios 的 js 文件

    <script src="js/axios-0.18.0.js"></script>
    
  • 使用axios 发送请求,并获取响应结果

    • 发送 get 请求

      axios({
          method:"get",
          url:"http://localhost:8080/ajax-demo1/aJAXDemo1?username=zhangsan"
      }).then(function (resp){
          alert(resp.data);
      })
      
    • 发送 post 请求

      axios({
          method:"post",
          url:"http://localhost:8080/ajax-demo1/aJAXDemo1",
          data:"username=zhangsan"
      }).then(function (resp){
          alert(resp.data);
      });
      

axios() 是用来发送异步请求的,小括号中使用 js 对象传递请求相关的参数:

  • method 属性:用来设置请求方式的。取值为 get 或者 post
  • url 属性:用来书写请求的资源路径。如果是 get 请求,需要将请求参数拼接到路径的后面,格式为: url?参数名=参数值&参数名2=参数值2
  • data 属性:作为请求体被发送的数据。也就是说如果是 post 请求的话,数据需要作为 data 属性的值。

then() 需要传递一个匿名函数。我们将 then() 中传递的匿名函数称为 回调函数,意思是该匿名函数在发送请求时不会被调用,而是在成功响应后调用的函数。而该回调函数中的 resp 参数是对响应的数据进行封装的对象,通过 resp.data 可以获取到响应的数据。

4.2 快速入门

4.2.1 后端实现

定义一个用于接收请求的servlet,代码如下:

@WebServlet("/axiosServlet")
public class AxiosServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("get...");
        //1. 接收请求参数
        String username = request.getParameter("username");
        System.out.println(username);
        //2. 响应数据
        response.getWriter().write("hello Axios~");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("post...");
        this.doGet(request, response);
    }
}
4.2.2 前端实现
  • 引入 js 文件

    <script src="js/axios-0.18.0.js"></script>
    
  • 发送 ajax 请求

    get 请求

    axios({
        method:"get",
        url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan"
    }).then(function (resp) {
        alert(resp.data);
    })
    

    post 请求

    axios({
        method:"post",
        url:"http://localhost:8080/ajax-demo/axiosServlet",
        data:"username=zhangsan"
    }).then(function (resp) {
        alert(resp.data);
    })
    

4.3 请求方法别名

为了方便起见, Axios 已经为所有支持的请求方法提供了别名。如下:

  • get 请求 : axios.get(url[,config])

  • delete 请求 : axios.delete(url[,config])

  • head 请求 : axios.head(url[,config])

  • options 请求 : axios.option(url[,config])

  • post 请求:axios.post(url[,data[,config])

  • put 请求:axios.put(url[,data[,config])

  • patch 请求:axios.patch(url[,data[,config])

而我们只关注 get 请求和 post 请求。

入门案例中的 get 请求代码可以改为如下:

axios.get("http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan").then(function (resp) {
    alert(resp.data);
});

入门案例中的 post 请求代码可以改为如下:

axios.post("http://localhost:8080/ajax-demo/axiosServlet","username=zhangsan").then(function (resp) {
    alert(resp.data);
})

5.JQuery发送Ajax请求

5.1 通用

//请求参数
var list = {};

$.ajax({
    //请求方式
    type : "POST",
    //请求的媒体类型
    contentType: "application/json;charset=UTF-8",
    //请求地址
    url : "http://localhost/admin/list/",
    //数据,json字符串
    data : JSON.stringify(list),
    //请求成功
    success : function(result) {
    console.log(result);
    },
    //请求失败,包含具体的错误信息
    error : function(e){
        console.log(e.status);
        console.log(e.responseText);
    }
});

5.2 get

//function(data)是指回流函数,data是写回在缓存中的数据
//$.get("AjaxServlet",{username:"zhangsan"}, function(data) {}这样子写也是一样的,最后get请求都会带随参数可见
$.get("AjaxServlet?username=zhangsan", function(data) {
    alert("Data: " + data);
});
	

5.3 post

//function(data)是指回流函数,data是写回在缓存中的数据
$.post("AjaxServlet",{username:"lisi"}, function(data) {
    alert("Data: " + data);
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值