简单学习Vue与Axios的使用

简单学习Vue与Axios的使用,第1张

1.AxiosAjax的一个框架,简化Ajax *** 作。

2.Axios执行Ajax *** 作的步骤:

(1)添加并引入axiosjs文件

<script language="JavaScript" src="script/vue.js">script>
<script language="JavaScript" src="script/axios.min.js">script>

(2)客户端向服务器端发送带有参数值的异步请求

第一种:客户端向服务器端异步发送普通参数值

  • 基本格式: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 可以查看错误的信息
    
  • 代码演示:

    【demo01.html】

    <head>
        <meta charset="UTF-8">
        <title>演示Axios发送普通参数值给服务器端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:{
                        axios01:function () {
                            axios({
                                method:"POST",
                                url:"axios01.do",
                                params:{
                                    uname:vue.uname,
                                    pwd:vue.pwd
                                }
                            })
                                .then(function (value) {
                                    console.log(value);
                                })
                                .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="axios01" value="发送一个带普通请求参数值的异步请求">
        div>
    body>
    

    【Axios01Servlet.java】

    @WebServlet("/axios01.do")
    public class Axios01Servlet extends HttpServlet {
        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
    
            String uname = request.getParameter("uname");
            String pwd = request.getParameter("pwd");
    
            System.out.println("uname=" + uname);
            System.out.println("pwd=" + pwd);
    
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(uname+"_"+pwd);
        }
    }
    
    

第二种:客户端向服务器发送JSON格式的数据

  • JSON:是一种数据格式

    • XML也是一种数据格式,XML格式表示两个学生信息的代码如下:

      <students>
          <student sid = "s001">
              <sname>Jimsname>
              <age>10age>
          student>
          <student sid = "s002">
              <sname>Linasname>
              <age>14age>
          student>
      students>
      
    • JSON格式表示两个学生信息的代码如下:

      [{sid:"s001",age:10},{sid:"s002",age:14}]
      
  • JSON表达数据更简洁,更能够节约网络带宽

  • 客户端发送JSON格式的数据给服务器端

    • 客户端中params需要修改成:data
    • 服务器获取参数值不再是 request.getParameter()
  • 客户端收到的内容为:{"uname":"lina","pwd":"ok"}

    代码演示:

    【demo02.html】

    axios({
    	method:"POST",
    	url:"axios02.do",
    	data:{
    		uname:vue.uname,
    		pwd:vue.pwd
    		}
    	})
    	.then(function (value) {
    		console.log(value);
    	})
    	.catch(function (reason) {
    		console.log(reason);
    	});
    

    【Axios02Servlet.java】

    @WebServlet("/axios02.do")
    public class Axios02Servlet extends HttpServlet {
        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            StringBuffer stringBuffer = new StringBuffer("");
    
            BufferedReader bufferedReader = request.getReader();
            String str = null;
            while ((str= bufferedReader.readLine()) != null) {
                stringBuffer.append(str);
            }
            str = stringBuffer.toString();
    
            //已知String 需要转换成Java Object
    
            Gson gson = new Gson ();
            //Gson有两个API
            //1.fromJson(String,T) 将字符串转化成Java Object
            //2.toJson(Java Object) 将Java Object转化成json字符串,这样才能响应给客户端
            User user = gson.fromJson(str,User.class);
            System.out.println(user);
        }
    }
    

(3)服务器端给客户端响应JSON格式的字符串,然后客户端需要将字符串转化成JS Object

【demo03.html】

axios({
	method:"POST",
	url:"axios02.do",
	data:{
		uname:vue.uname,
		pwd:vue.pwd
		}
	})
	.then(function (value) {
		var data = value.data;
        //data对应的数据:{uname:"dc",pwd:"ok"}
        vue.uname = data.uname;
        vue.pwd = data.pwd;

        //此处value中的data返回的实时js object,因此可以直接点出属性
        //如果获取的是一个字符串:“{uname:"dc",pwd:"ok"}”

        //js语言中,也有字符串和js对象之间互换的API
        //string JSON.stringify(object)   object -> string
        //object JSON.parse(string)  string -> object
	})
	.catch(function (reason) {
		console.log(reason);
	});

【Axios03Servlet.java】

@WebServlet("/axios03.do")
public class Axios03Servlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        StringBuffer stringBuffer = new StringBuffer("");

        BufferedReader bufferedReader = request.getReader();
        String str = null;
        while ((str= bufferedReader.readLine()) != null) {
            stringBuffer.append(str);
        }
        str = stringBuffer.toString();

        //已知String 需要转换成Java Object

        Gson gson = new Gson ();
        //Gson有两个API
        //1.fromJson(String,T) 将字符串转化成Java Object
        //2.toJson(Java Object) 将Java Object转化成json字符串,这样才能响应给客户端
        User user = gson.fromJson(str,User.class);
        user.setUname("dc");
        user.setPwd("121524");

        //假设user是从数据库查出来的,需要将其转化成json格式的字符串,然后响应给客户端
        String userJsonStr = gson.toJson(user);
        response.setCharacterEncoding("utf-8");
        //
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(userJsonStr);
   	 }	
}

3.js语言中,也有字符串和js对象之间互换的API

  • string -> object

    var str = "{\"uname\":\"lina\",\"age\":20}";
    var user = JSON.parse(str);
    alert(typeof user);
    alert(user.uname+"_"+user.age);
    
  • object -> string

    var user = {"uname":"lina","age":99};
    alert(typeof user);
    var userStr = JSON.stringify(user);
    alert(typeof userStr);
    alert(userStr);
    

4. *** 作图

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/889923.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-14
下一篇 2022-05-14

发表评论

登录后才能评论

评论列表(0条)

保存