您当前的位置: 首页 >  json

梁云亮

暂无认证

  • 2浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Vue插件之fetch-jsonp

梁云亮 发布时间:2020-11-11 12:40:11 ,浏览量:2

简介

fetch-jsonp支持JSONP,跨域

步骤: 1、安装:cnpm install fetch-jsonp –save 2、哪里用哪里引入

示例:
  • 服务器端代码:
@WebServlet(urlPatterns = "/servlet/vue")
public class VueServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        String callback = request.getParameter("callback");
        PrintWriter out = response.getWriter();

        List userList = new ArrayList();
        userList.add(new User(11, "zhangsan", '女'));
        userList.add(new User(22, "lisi", '女'));
        userList.add(new User(33, "wanger", '女'));
        userList.add(new User(44, "mazi", '男'));

        String json = new Gson().toJson(userList);
        System.out.println("json " + json);
        out.write(callback + "(" + json + ")");
    }
}
  • 前端代码 第一步:安装

npm install fetch-jsonp ;

第二步:App.vue页面


  
    请求数据
    
      
        {{item}}
      
    
  


  import fetchJsonp from 'fetch-jsonp';   //引用
  export default {   
    name: 'app',
    data() {
      return {
        users: []
      }
    },
    methods: {
      getData() {
        var url = 'http://127.0.0.1:8088/servlet/vue';
        fetchJsonp(url, {jsonpCallback: 'callback'})
          .then((response) => {
            console.log(response);
            console.log(response.json());
            return response.json();
          }).then((json) => {
          this.users = json;	// 在此处进行接收数据之后的操作
        }).catch((error) => {
          console.log(error);	// 此处是数据请求失败后的处理
        })
      }
    }, mounted() { //新新的时候数据就显示出来
      this.getData();
    }
  }

关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.0451s