Axios Ajax


前言

发送普通参数请求及相应普通文本及异常情况,客户端发送json格式的数据以及服务端的响应。


提示:以下是本篇文章正文内容,下面案例可供参考

一.在前端页面引入开发环境

<script type="text/javascript" src="/demo/static/vue.js"></script>
<script type="text/javascript" src="/demo/static/axios.min.js"></script>

二.发送普通请求参数

①前端代码

HTML标签:

    <div id="app">
        <button @click="commonParam">普通请求参数</button>
    </div>

Vue+axios代码:

new Vue({
   "el":"#app",
   "data":{},
   "methods":{
       "commonParam":function () {
           axios({
               "method":"post",
               "url":"/demo/AjaxServlet?method=commonParam",
               "params":{
                   "userName":"tom",
                   "userPwd":"123456"
               }
           }).then(function (response) {
               console.log(response);
           }).catch(function (error) {
               console.log(error);
           });
       }
   }
});

效果:所有请求参数都被放到URL地址后面了,哪怕我们现在用的是POST请求方式。

./images

②后端代码

public class AjaxServlet extends ModelBaseServlet {
    protected void commonParam(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String userName = request.getParameter("userName");
        String userPwd = request.getParameter("userPwd");

        System.out.println("userName = " + userName);
        System.out.println("userPwd = " + userPwd);

        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("服务器端返回普通文本字符串作为响应");

    }
}

P.S.:由于我们不需要Thymeleaf了,所以ModelBaseServlet可以跳过ViewBaseServlet直接继承HttpServlet。

./images

③axios程序接收到的响应对象结构

./images

属性名作用
config调用axios(config对象)方法时传入的JSON对象
data服务器端返回的响应体数据
headers响应消息头
request原生JavaScript执行Ajax操作时使用的XMLHttpRequest
status响应状态码
statusText响应状态码的说明文本

④服务器端处理请求失败后

catch(function (error) {     // catch()服务器端处理请求出错后,会调用

    console.log(error);         // error就是出错时服务器端返回的响应数据
    console.log(error.response);        // 在服务器端处理请求失败后,获取axios封装的JSON格式的响应数据对象
    console.log(error.response.status); // 在服务器端处理请求失败后,获取响应状态码
    console.log(error.response.statusText); // 在服务器端处理请求失败后,获取响应状态说明文本
    console.log(error.response.data);   // 在服务器端处理请求失败后,获取响应体数据

});

在给catch()函数传入的回调函数中,error对象封装了服务器端处理请求失败后相应的错误信息。其中,axios封装的响应数据对象,是error对象的response属性。response属性对象的结构如下图所示:

./images

可以看到,response对象的结构还是和then()函数传入的回调函数中的response是一样的:

./images

回调函数:开发人员声明,但是调用时交给系统来调用。像单击响应函数、then()、catch()里面传入的都是回调函数。回调函数是相对于普通函数来说的,普通函数就是开发人员自己声明,自己调用:

function sum(a, b) {
    return a+b;
}

var result = sum(3, 2);
console.log("result="+result);

三、发送请求体JSON

①前端代码

HTML代码:

<button @click="requestBodyJSON">请求体JSON</button>

Vue+axios代码:

"methods":{
    "requestBodyJSON":function () {
        axios({
            "method":"post",
            "url":"/demo/AjaxServlet?method=requestBodyJSON",
            "data":{
                "stuId": 55,
                "stuName": "tom",
                "subjectList": [
                    {
                        "subjectName": "java",
                        "subjectScore": 50.55
                    },
                    {
                        "subjectName": "php",
                        "subjectScore": 30.26
                    }
                ],
                "teacherMap": {
                    "one": {
                        "teacherName":"tom",
                        "tearcherAge":23
                    },
                    "two": {
                        "teacherName":"jerry",
                        "tearcherAge":31
                    },
                },
                "school": {
                    "schoolId": 23,
                    "schoolName": "atguigu"
                }
            }
        }).then(function (response) {
            console.log(response);
        }).catch(function (error) {
            console.log(error);
        });
    }
}

效果:

./images

P.S.:Chrome浏览器中将『请求负载』显示为英文:『Request Payload』。

②后端代码

  • [1]加入Gson包
    Gson是Google研发的一款非常优秀的JSON数据解析和生成工具,它可以帮助我们将数据在JSON字符串和Java对象之间互相转换。

./images

  • [2]Servlet代码
protected void requestBodyJSON(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // 1.由于请求体数据有可能很大,所以Servlet标准在设计API的时候要求我们通过输入流来读取
    BufferedReader reader = request.getReader();

    // 2.创建StringBuilder对象来累加存储从请求体中读取到的每一行
    StringBuilder builder = new StringBuilder();

    // 3.声明临时变量
    String bufferStr = null;

    // 4.循环读取
    while((bufferStr = reader.readLine()) != null) {
        builder.append(bufferStr);
    }

    // 5.关闭流
    reader.close();

    // 6.累加的结果就是整个请求体
    String requestBody = builder.toString();

    // 7.创建Gson对象用于解析JSON字符串
    Gson gson = new Gson();

    // 8.将JSON字符串还原为Java对象
    Student student = gson.fromJson(requestBody, Student.class);
    System.out.println("student = " + student);

    System.out.println("requestBody = " + requestBody);

    response.setContentType("text/html;charset=UTF-8");
    response.getWriter().write("服务器端返回普通文本字符串作为响应");
}

P.S.:看着很麻烦是吧?别担心,将来我们有了SpringMVC之后,一个@RequestBody注解就能够搞定,非常方便!

四、服务器端返回JSON数据

①前端代码

axios({
    "method":"post",
    "url":"/demo/AjaxServlet?method=responseBodyJSON"
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

then()中获取到的response在控制台打印效果如下:我们需要通过data属性获取响应体数据

./images

②后端代码

  • [1]加入Gson包
    仍然需要Gson支持,不用多说

./images

  • [2]Servlet代码
protected void responseBodyJSON(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // 1.准备数据对象
    Student student = new Student();
    student.setStuId(10);
    student.setStuName("tom");
    student.setSchool(new School(11,"atguigu"));
    student.setSubjectList(Arrays.asList(new Subject("java", 95.5), new Subject("php", 93.3)));

    Map<String, Teacher> teacherMap = new HashMap<>();
    teacherMap.put("t1", new Teacher("lili", 25));
    teacherMap.put("t2", new Teacher("mary", 26));
    teacherMap.put("t3", new Teacher("katty", 27));

    student.setTeacherMap(teacherMap);

    // 2.创建Gson对象
    Gson gson = new Gson();

    // 3.将Java对象转换为JSON对象
    String json = gson.toJson(student);

    // 4.设置响应体的内容类型
    response.setContentType("application/json;charset=UTF-8");
    response.getWriter().write(json);

}

五、总结

1.客户端向服务器端异步发送普通参数值

  • 基本格式: axios().then().catch()
  • 示例:
axios({
        method:"POST",
        url:"....",
        params:{
            uname:"lina",
            pwd:"ok"
        }
      })
      .then(function(value){})          //成功响应时执行的回调        value.data可以获取到服务器响应内容
      .catch(function(reason){});       //有异常时执行的回调          reason.response.data可以获取到响应的内容

                                                                   reason.message / reason.stack 可以查看错误的信息

2. 客户端向服务器发送JSON格式的数据

  • 1客户端中params需要修改成: data:
  • 2 服务器获取参数值不再是 request.getParameter()…
    而是:
    StringBuffer stringBuffer = new StringBuffer("");
       BufferedReader bufferedReader = request.getReader();
       String str = null ;
       while((str=bufferedReader.readLine())!=null){
           stringBuffer.append(str);
       }
       str = stringBuffer.toString() ;
  • 3 我们会发现 str的内容如下:
    {“uname”:“lina”,“pwd”:“ok”}
  • 4 服务器端给客户端响应JSON格式的字符串,然后客户端需要将字符串转化成js Object

3.js object 与 js string

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>03.演示Axios发送异步请求给服务器端,服务器响应json格式的数据给客户端</title>
    <script language="JavaScript" src="script/vue.js"></script>
    <script language="JavaScript" src="script/axios.min.js"></script>
    <script language="JavaScript">
        window.onload=function(){
            var vue = new Vue({
                "el":"#div0",
                data:{
                    uname:"lina",
                    pwd:"ok"
                },
                methods:{
                    axios03:function(){
                        axios({
                            method:"POST",
                            url:"axios03.do",
                            data:{
                                uname:vue.uname,
                                pwd:vue.pwd
                            }
                        })
                            .then(function (value) {
                                var data = value.data;
                                // data对应的数据:
                                // {uname:"鸠摩智",pwd:"ok"}
                                vue.uname=data.uname;
                                vue.pwd=data.pwd;

                                //此处value中的data返回的是 js object,因此可以直接点出属性
                                //如果我们获取的是一个字符串:  "{uname:\"鸠摩智\",pwd:\"ok\"}"

                                //js语言中 也有字符串和js对象之间互转的API
                                //string JSON.stringify(object)     object->string
                                //object JSON.parse(string)         string->object
                            })
                            .catch(function (reason) {
                                console.log(reason);
                            });
                    }
                }
            });
        }
    </script>
</head>
<body>
    <div id="div0">
        uname:<input type="text" v-model="uname"/><br/>
        pwd:<input type="text" v-model="pwd"/><br/>
        <input type="button" @click="axios03" value="服务器响应json格式的数据给客户端"/>
    </div>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>04.JS中的字符串和Object之间互转的API</title>
    <script language="JavaScript">
        function hello01(){
            /*
            //1. js string - > js object
            var str = "{\"uname\":\"lina\",\"age\":20}";
            var user = JSON.parse(str);
            alert(typeof user);
            alert(user.uname+"_"+user.age);
            */

            //2. js object -> js string
            var user = {"uname":"lina","age":99};
            alert(typeof user);
            var userStr = JSON.stringify(user);
            alert(typeof userStr);
            alert(userStr);
        }
    </script>
</head>
<body>
    <div id="div0">
        <input type="button" value="确定" onclick="hello01()"/>
    </div>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值