vue中使用Ajax(axios)

时间:2021-09-16 05:18:06

  Vue.js 2.0 版本推荐使用 axios 来完成 ajax 请求。Axios 是一个基于 Promise 的 HTTP 库,可以用在浏览器和 node.js 中。

  axios中文文档库:http://www.axios-js.com/zh-cn/docs/

1.Axios简单使用

1.axios发送简单的get请求

后台:

    @RequestMapping("/index")
    @ResponseBody
    public Map index(HttpServletRequest request, HttpServletResponse response, @RequestParam Map condition) {
        System.out.println(condition);
        // 允许ajax跨域请求
        response.setHeader("Access-Control-Allow-Origin", "*");
        return condition;
    }

 

前台:

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/axios.min.js" type="text/javascript" charset="utf-8"></script>
    </head>

    <body>
        <script>
            // 为给定 ID 的 user 创建请求
            axios.get(http://localhost:8088/weixin/test/index.html?name=zs)
                .then(function(response) {
                    console.log(response);
                })
                .catch(function(error) {
                    console.log(error);
                });
        </script>
    </body>

</html>

结果:

vue中使用Ajax(axios)

 

上面的请求还可以:

        <script>
            // 上面的请求也可以这样做
            axios.get(‘http://localhost:8088/weixin/test/index.html‘, {
                    params: {
                        name: ‘zs2‘
                    }
                })
                .then(function(response) {
                    console.log(response);
                })
                .catch(function(error) {
                    console.log(error);
                });
        </script>

 

2.发送POST请求

后台需要过滤器中允许跨域请求:

package cn.qlq.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

/**
 * 允许跨域请求
 */
@WebFilter(filterName = "corsFilter", urlPatterns = "/*")
public class CorsFilter implements Filter {
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println(1);
        HttpServletResponse response2 = (HttpServletResponse) response;
        response2.setHeader("Access-Control-Allow-Origin", "*"); // 解决跨域访问报错
        response2.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response2.setHeader("Access-Control-Max-Age", "3600"); // 设置过期时间
        response2.setHeader("Access-Control-Allow-Headers",
                "Origin, X-Requested-With, Content-Type, Accept, client_id, uuid, Authorization");
        response2.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // 支持HTTP
                                                                                        // 1.1.
        response2.setHeader("Pragma", "no-cache"); // 支持HTTP 1.0.
                                                    // response.setHeader("Expires",
                                                    // "0");

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}

Controller代码:

    @RequestMapping("/index")
    @ResponseBody
    public Map index(HttpServletRequest request, HttpServletResponse response, @RequestBody Map condition) {
        System.out.println(condition);

        return condition;
    }

 

前台代码:

        <script>
            axios.post(‘http://localhost:8088/weixin/test/index.html‘, {
                    firstName: ‘Fred‘,
                    lastName: ‘Flintstone‘
                })
                .then(function(response) {
                    console.log(response);
                })
                .catch(function(error) {
                    console.log(error);
                });
        </script>

结果:

vue中使用Ajax(axios)

 

post的请求头Content-Type是application/json,发送JSON数据请求

vue中使用Ajax(axios)

 

3.响应结构

{
  // `data` 由服务器提供的响应
  data: {},

  // `status` 来自服务器响应的 HTTP 状态码
  status: 200,

  // `statusText` 来自服务器响应的 HTTP 状态信息
  statusText: ‘OK‘,

  // `headers` 服务器响应的头
  headers: {},

   // `config` 是为请求提供的配置信息
  config: {},
 // ‘request‘
  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance the browser
  request: {}
}

 

2.vue中使用axios

1. 简单使用

后端代码:

    @RequestMapping("/index")
    @ResponseBody
    public Map index(HttpServletRequest request, HttpServletResponse response, @RequestBody Map condition) {
        condition.put("name", "zs");
        condition.put("age", 25);
        return condition;
    }

 

前台:(请求后台的JSON数据,并且将得到的数据直接赋值给自己的data属性,自己的data原来为null)

<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="js/axios.min.js" type="text/javascript" charset="utf-8"></script>
    </head>

    <body>
        <div id="app">
            <h1>{{ data.name }} - {{ data.age }}</h1>
        </div>
        <script type="text/javascript">
            new Vue({
                el: ‘#app‘,
                data: {
                    data: null
                },
                mounted() {
                    axios
                        .post(‘http://localhost:8088/weixin/test/index.html‘, {
                            ‘test‘: 123
                        })
                        .then(response => (this.data = response.data))
                        .catch(function(error) { // 请求失败处理
                            console.log(error);
                        });
                }
            })
        </script>
    </body>

</html>

结果:

vue中使用Ajax(axios)

 

2. 请求图片流

  未完待续。。。